jQuery 启用基于第一个选项的下拉列表


jQuery enable dropdown based on first option

我试图通过谷歌找到问题的答案,但收效甚微。我是jQuery的新手,所以答案可能很简单。

我的表单上有 2 个下拉字段,都是从数据库中填充的。

<select name="fld_1" id="fld_1">
    ..set of options from DB..
</select>
<select disabled name="fld_2" id="fld_2">
    Please select value from field above
</select>

第二个字段处于禁用状态,直到用户从第一个字段中选择一个值。该值被传递给运行数据库检查的 php 文件,并返回一组选项。所有这些都由jQuery控制:

$(function() {
    $('#fld_1').change(function() {
        $('#fld_2').load('fetch.php?ccID=' + $('#fld_1').val());
    });
});

如果找到结果,PHP 输出:

<option value="aaa">
    aaa - descr
</option>
<option value="bbb">
    bbb - descr
</option> ....

PHP 输出未找到结果:

<option value="0">
    No accounts found for this cost center
</option>

我想要实现的是: if the value of the first option is 0 keep the dropdown disabled, if anything else remove the disable attribute .

感谢您的帮助

我建议:

$('#fld_1').change(function(){
    $('#fld_2').prop('disabled', $(this).val() === 0);
}).change();

JS小提琴演示。

引用:

  • change() .
  • prop() .