简体   繁体   中英

Select one checkbox and disable others

I am trying to select one checkbox and disable all others. The problem is I am figure out how to do the reverse. Uncheck and enable all checkboxes.

Html: This is a dynamic list of checkboxes

<input type="checkbox" id="mycheckbox1"/>
<input type="checkbox" id="mycheckbox2"/>
<input type="checkbox" id="mycheckbox3"/>

I have tried this:

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

Much simpler to use not() inside event handler to target all the others.

Use the checked state of current checkbox to determine disabled state

 $(':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"/> 

Sounds like for what you are trying to achieve a radio button list may be more appropriate.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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