这个案例是关于下拉选项后的动态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无效。
答案 0 :(得分:1)
您的PHP代码循环在while
中,请看
while($row = mysql_fetch_assoc($res)) { ?>
<div class="col-sm-10">
<select name="categorie" class="form-control" id="selectMe">
因此,您有许多实例id="selectMe"
这是不正确的HTML。这是一个逻辑错误
您需要为id
<select>
顺便说一句,如果你在一个事件监听器中,你可以通过$(this).val()
访问该值。它将准确地解决已更改的元素。
答案 1 :(得分:0)
我找到了正确的解决方案。见下文:
<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>