如何基于另一个下拉菜单禁用下拉选项值

问题描述 投票:0回答:1

搜索google和堆栈溢出,找不到解决方案。

我在MVC核心视图中有两个下拉菜单

下拉菜单如下:

<option>A</option>
<option>B</option>

第二个下拉菜单如下:

<option>A1</option>
<option>A2</option>
<option>A3</option>
<option>B1</option>
<option>B2</option>

当在第一个下拉列表中选择B时,我需要在第二个下拉列表中禁用A1,A2和A3,而在第一个下拉列表中选择A时,则禁用B1和B2。

我尝试了以下操作,但不起作用:

    $('#FirstDropDown').change(function () {
        var data = $(this).val();
        if (data == "A") {
            $("#SecondDropDown option[value='A1']").attr('disabled', 'disabled');
            $("#SecondDropDown option[value='A2']").attr('disabled', 'disabled');
            $("#SecondDropDown option[value='A3']").attr('disabled', 'disabled');
        }
    });
dropdown option disable
1个回答
0
投票

[当您尝试访问$("#SecondDropDown option[value='A1']")中的值时,该值周围不应包含单引号,而应将其用于HTML value属性,因此这样更合适:

$('#FirstDropDown').change(function () {
    var data = $(this).val();
    if (data == "A") {
        $("#SecondDropDown option[value=B1]").attr('disabled', 'disabled');
        $("#SecondDropDown option[value=B2]").attr('disabled', 'disabled');
        $("#SecondDropDown option[value=A1]").prop('disabled', false);
        $("#SecondDropDown option[value=A2]").prop('disabled', false);
        $("#SecondDropDown option[value=A3]").prop('disabled', false);
    }
    if (data == "B") {
        $("#SecondDropDown option[value=A1]").attr('disabled', 'disabled');
        $("#SecondDropDown option[value=A2]").attr('disabled', 'disabled');
        $("#SecondDropDown option[value=A3]").attr('disabled', 'disabled');
        $("#SecondDropDown option[value=B1]").prop('disabled', false);
        $("#SecondDropDown option[value=B2]").prop('disabled', false);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="FirstDropDown">
    <option>A</option>
    <option>B</option>
</select>

<select id="SecondDropDown">
    <option value="A1">A1</option>
    <option value="A2">A2</option>
    <option value="A3">A3</option>
    <option value="B1">B1</option>
    <option value="B2">B2</option>
</select>

请注意,当用户切换时,您必须禁用/重新启用相反的字母,因为这可能会发生。我使用了prop()方法。

© www.soinside.com 2019 - 2024. All rights reserved.