[英]Select one checkbox and disable others
我試圖選擇一個復選框並禁用所有其他復選框。 問題是我想出如何做相反的事情。 取消選中並啟用所有復選框。
HTML:這是復選框的動態列表
<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>
我已經試過了:
var checkboxlist = $("input:checkbox");
$('.checkbox').on("change", function () {
var itemId = $(this).attr("id");
$.each(checkboxlist, function (index, value) {
var id = $(value).attr("id");
if (!(itemId === id)) {
$(value).attr("disabled", "true");
}
});
})
在事件處理程序中使用not()
來將所有其他目標作為目標要容易得多。
使用當前復選框的checked
狀態來確定禁用狀態
$(':checkbox').change(function(){ // "this" is current checkbox $(':checkbox').not(this).prop('disabled', this.checked); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="mycheckbox1"/> <input type="checkbox" id="mycheckbox2"/> <input type="checkbox" id="mycheckbox3"/>
聽起來更像是您想要實現單選按鈕列表的方式。
<input type="radio" name="myRadio" value="myRadio1"/>
<input type="radio" name="myRadio" value="myRadio2"/>
<input type="radio" name="myRadio" value="myRadio3"/>
var checkboxlist = $("input:checkbox"); $('.checkbox').on("change", function () { var itemId = $(this).attr("id"); if ($(this).is(':checked')) { $.each(checkboxlist, function (index, value) { var id = $(value).attr("id"); if (!(itemId === id)) { $(value).attr("disabled", "true"); } }); } else { $.each(checkboxlist, function (index, value) { var id = $(value).attr("id"); if (!(itemId === id)) { $(value).attr("disabled", "false"); } }); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.