繁体   English   中英

复选框启用基于下拉选项禁用

[英]checkbox enable disable based on dropdown option

我创建了一个下拉列表和几个复选框。 复选框基于选定的下拉选项启用和禁用。

这是代码:

<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时,两个值=“ 2”的孩子和食物都将禁用,但是当我从每个复选框中选择theta时将被禁用,这不应该是这样。 只有值=“ 1”应该被禁用,例如,茶和卡普里岛。

帮助纠正它与代码有关的问题。 提前致谢。

您需要在每次选择更改之间撤消操作 ,以便再次启用已禁用的功能,因此,如果在函数开始处添加这两行,它将起作用

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

旁注,如“ Ezequias Dinella”在他的回答中所示,要启用/禁用所有功能,还可以删除属性,例如$(“。dissable”)。prop(“ disabled”,true);。

样品

 $("#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> 

一种简单的方法是在禁用所选复选框之前启用所有复选框,以确保仅禁用所需的复选框。

// 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM