这是我第一次发帖,我刚开始学习如何编写js代码。 所以基本上,我想知道的是如何根据用户从下拉列表中选择的项目显示或隐藏内容。
这是php代码:
<script src="js/category.js"></script>
<?php
include 'dbh.php';
$sqli='SELECT * FROM categories';
$getdata=mysqli_query($conn,$sqli);
echo "
<form action='category_input.php' method='POST' id='categoryform'>
Category: <select name='category_id'>";
while($row = mysqli_fetch_assoc($getdata))
{
echo
'<option value='.$row['id'].'>'.$row['category_name'].'</option>';
};
echo '</select></form>';
echo "
<div style='display:none;' id='computer'>
<br><br>
Part Number:
<input type='text' style='width:200px' name='part_number' placeholder='Serial Number'>
<br><br>
Serial Number:
<input type='text' style='width:200px' name='serial_number' placeholder='Serial Number'>
<br><br>
<label>Description</label>
<textarea rows='4' cols='50' name='description' form='categoryform'>
</textarea>
<br><br>
</div>
";
echo "
<div style='display:none;' id='peripheral'>
<br><br>
Brand:
<input type='text' style='width:200px' name='brand' placeholder='Brand'>
<br><br>
Type:
<input type='text' style='width:200px' name='type' placeholder='Type'>
<br><br>
Type:
<input type='text' style='width:200px' name='type' placeholder='Type'>
<br><br>
Part Number:
<input type='text' style='width:200px' name='part_number' placeholder='Part Number'>
<br><br>
Serial Number:
<input type='text' style='width:200px' name='serial_number' placeholder='Serial Number'>
<br><br>
</div>";
这是category.js代码:
var selectedVal = document.getElementsByName("category_id").value;
if(selectedVal == '1') // Put any condition here selectedVal == '1'
{
var element = document.getElementById('computer');
element.style.visibility = 'hidden'; // Hide
}
else
{
var element = document.getElementById('computer');
element.style.visibility = 'visible'; // Show
}
这是category_name列表:
PC
Notebook
Server
Scanner
Printer
DVD
AccessPoint/Wireless
Mikrotik
Fingerprint
Monitor
Rack Server
DVR
FotoCopy
TV
Modem
Camera
External Storage
ThinClient
Projector
STB BOX(Indihome TV)
VOIP
UPS
Switch
Keyboard
Mouse
当我点击category_id = 1时,我试图检查它是否有效但是它没有回显div id =“computer”
很抱歉这篇长篇文章,请告诉我是否需要添加更多信息和反馈,以便我今后发布帖子。
编辑:添加了js
答案 0 :(得分:1)
试试这个:
var selectedVal = document.getElementsByName("category_id").value;
if(selectedVal == '1') // Put any condition here selectedVal == '1'
{
var element = document.getElementById('id');
element.style.visibility = 'hidden'; // Hide
}
else
{
var element = document.getElementById('id');
element.style.visibility = 'visible'; // Show
}
答案 1 :(得分:0)
<强>更新强> 所以我找到了一个有效的解决方案:
<script>
function populateField() {
selectedVal = document.getElementById('select').value;
if((selectedVal == '1') || (selectedVal == '2') || (selectedVal == '3'))
{
$("#computer").show();
$("#peripheral").hide();
}
else
{
$("#computer").hide();
$("#peripheral").show();
}
}
使用这个:
<select style='width:100%;' name='category_name' id='select' onchange='populateField()'>