复选框根据下拉选项启用禁用

checkbox enable disable based on dropdown option

本文关键字:启用 选项 复选框      更新时间:2023-09-26

我创建了一个下拉框和几个复选框。复选框根据所选的下拉选项启用和禁用。

代码如下:

<select id="Objective" form="theForm" name="category" >
    <option value="pi">Pipi</option>
    <option value="theta">thethaatha</option>
    <option value="sigma">sigmama</option>
</select>
<div>
    <input type="checkbox" class="dissable" onclick="check();" value="1" /> Teas<br>
    <input type="checkbox" class="dissable" onclick="check();" value="1" /> Capri<br>
    <input type="checkbox" class="dissable" onclick="check();" value="2" /> Kids <br>
    <input type="checkbox" class="dissable" onclick="check();" value="2" /> Food <br>
</div>
<script>
$("#Objective").on("change", function () {
    if ($(this).val() == "theta") {
        $(".dissable[value='1']").prop("disabled", true);
    } else if ($(this).val() == "pi") {
        $(".dissable[value='2']").prop("disabled", true);
    } else {
        //donothing
    }
}).trigger('change');
</script>

每当我从下拉框中选择pi时,它都很好,value ="2"孩子和食物都被禁用,但当我从每个复选框中选择theta时,它都被禁用,这不应该像这样。只有value ="1"应该被禁用,即tea和capri。

帮助纠正代码的问题。

一种简单的方法是在禁用选中的复选框之前启用所有复选框,以确保只有您想要禁用的复选框;

// enable all checkboxes
$(".dissable").prop("disabled", false);

,然后你可以禁用选定的:

// disabling some of them
$(".dissable[value='1']").prop("disabled", true);

工作示例:http://codepen.io/anon/pen/bwJaEp?editors=1010

您需要在每次选择更改之间撤销以便禁用的那个重新启用,因此如果您在函数开头添加这两行,它将起作用

    $(".dissable[value='1']").prop("disabled", true);
    $(".dissable[value='2']").prop("disabled", true);

旁注,正如"Ezequias Dinella"在他的回答中显示的那样,要启用/禁用所有你也可以删除属性,像这样$(". disable")。道具("禁用",真的);

示例

$("#Objective").on("change", function () {
    $(".dissable[value='1']").prop("disabled", false);
    $(".dissable[value='2']").prop("disabled", false);
  
    if ($(this).val() == "theta") {
        $(".dissable[value='1']").prop("disabled", true);
    } else if ($(this).val() == "pi") {
        $(".dissable[value='2']").prop("disabled", true);
    } else {
        //donothing
        $(".dissable[value='1']").prop("disabled", true);
        $(".dissable[value='2']").prop("disabled", true);
    }
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Objective" form="theForm" name="category" >
    <option value="pi">Pipi</option>
    <option value="theta">thethaatha</option>
    <option value="sigma">sigmama</option>
</select>
<div>
<input type="checkbox" class="dissable" onclick="check();" value="1" /> Teas<br>
<input type="checkbox" class="dissable" onclick="check();" value="1" /> Capri<br>
<input type="checkbox" class="dissable" onclick="check();" value="2" /> Kids <br>
<input type="checkbox" class="dissable" onclick="check();" value="2" /> Food <br>
</div>