[英]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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.