Javascript 不遵循下拉列表选择


Javascript is not following dropdown list choice

这种情况是关于下拉选项之后的动态div。如果您必须在下拉列表中做出选择,您看到的内容效果很好。此示例是关于一个修改页面,其中过去已经做出了选择,并且值来自数据库。

脚本:

$sql = "SELECT * FROM accountics WHERE id = '$id'";
$res = mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($res)) { ?>
<div class="col-sm-10">
  <select name="categorie" class="form-control" id="selectMe">
    <option selected value="<?php echo $row['categorie']; ?>"><?php echo $row['categorie']; ?></option>
 <?php                           
 $sql1 = "SELECT distinct naam FROM lijst_accountics_categorie";
 $res1 = mysql_query($sql1) or die (mysql_error());
 while($row = mysql_fetch_assoc($res1)) { 
 ?>                           
 <option value="<?php echo $row['naam']; ?>"><?php echo $row['naam']; ?></option>
 <?php 
 }
 $sql = "SELECT * FROM accountics WHERE id = '$id'";
 $res = mysql_query($sql) or die (mysql_error());
     while($row = mysql_fetch_assoc($res)) { 
 ?>                               
  </select>
</div>

现在我们有了div 的脚本:

<!-- Category is restaurant -->
<div id="Restaurant" class="group">
   <div class="col-sm-10">
      <input type="text" name="bedrag1_excl" class="form-control" id="field-1" value="<?php echo $row['bedrag1_excl']; ?>">
   </div>
</div>

<!-- If category is not Restaurant -->
<div id="Geen" class="group">
<div class="col-sm-10">
   <input type="text" name="bedrag_excl" class="form-control" id="field-1" value="<?php echo $row['bedrag_excl']; ?>">
</div>
</div>
</div>

在这里,我们有用于在下拉菜单后面调用div 的 javascript 代码。我认为这是不对劲的。价值"Geen"是一切不是餐厅的选择。

<script>
$(document).ready(function () {
   $('.group').hide();
   $('#Geen').show();
$('#selectMe').change(function () {
$('.group').hide();
var Restaurant = $("#selectMe").val();  
if(Restaurant === 'Restaurant') {
   $('#Restaurant').show();
} else {
   $('#Geen').show();
}   
})
});
</script>

如果我刷新此页面,则在下拉列表中很好地实现了这些值(从之前保存的数据库值中检索的值)。现在,您从下拉列表中做出不同的选择,然后必须将其设置为旧值,否则javascript将无法正常工作。

你的PHP代码在while循环,看看

while($row = mysql_fetch_assoc($res)) { ?>
    <div class="col-sm-10">
      <select name="categorie" class="form-control" id="selectMe">

因此,您有许多实例id="selectMe"
这是不正确的 HTML。这是一个逻辑错误。
您需要使用 CSS 类而不是 id<select>

顺便说一句,如果您在事件侦听器中,则可以通过$(this).val()访问该值。它将准确解决已更改的元素。

我找到了正确的解决方案。见下文:

<script>
$(document).ready(function () {
   $('.group').hide();
if($('#selectMe').val() === 'Restaurant') {
   $('#Restaurant').show();
}
else {
   $('#Geen').show();
}

$('#selectMe').change(function () {
   $('.group').hide();

if($('#selectMe').val() === 'Restaurant') {
   $('#Restaurant').show();
}
else {  
   $('#Geen').show();
}

  })
});
</script>