繁体   English   中英

选择一个复选框并禁用其他复选框

[英]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.

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