选中一个复选框并停用其他

时间:2017-05-14 21:45:37

标签: javascript jquery

我正在尝试选中一个复选框并禁用所有其他复选框。问题是我弄清楚如何反过来。取消选中并启用所有复选框。

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");
        } 
    });
})

3 个答案:

答案 0 :(得分:2)

在事件处理程序中使用not()来定位所有其他的更简单。

使用当前的checked状态复选框来确定禁用状态

&#13;
&#13;
$(':checkbox').change(function(){
     // "this" is current checkbox
     $(':checkbox').not(this).prop('disabled', this.checked);
});

   
&#13;
<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"/>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

听起来你试图获得单选按钮列表可能更合适。

<input type="radio" name="myRadio" value="myRadio1"/>
<input type="radio" name="myRadio" value="myRadio2"/>
<input type="radio" name="myRadio" value="myRadio3"/>

答案 2 :(得分:0)

&#13;
&#13;
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");
            } 
          });
        }
    })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;