JQuery - disable duplicate checkboxes when checked

后端 未结 1 567
野的像风
野的像风 2021-01-13 04:41

I have a list of checkboxes grouped into sections. Some of these checkboxes can appear in more than one section. What I would like to do is stop the user from selecting the

相关标签:
1条回答
  • 2021-01-13 05:22

    I wouldn't disable the checkboxes, I would just bind them together, so they change all like this:

    $('input[type=checkbox]').change(function(){
        name = $(this).attr('name');
        checked = $(this).attr('checked');
        // this will set all the checkboxes with the same name to the same status
        $('input[type=checkbox][name='+name+']').attr('checked',checked);
    });​
    

    working example


    Update: To disable other checkboxes:

    $('input[type=checkbox]').change(function(){
        name = $(this).attr('name');
        id = $(this).attr('id');
        checked = $(this).attr('checked');
        // disable all checkboxes except itself
        $('input[type=checkbox][name='+name+']:not(#'+id+')')
            .attr('disabled',checked);
    });​
    

    working example


    Update 2: To grey out the corresponding labels too:

    $('input[type=checkbox]').change(function(){
        name = $(this).attr('name');
        id = $(this).attr('id');
        checked = $(this).attr('checked');
        $('input[type=checkbox][name='+name+']:not(#'+id+')')
            .attr('disabled',checked)
            .each(function(){
                lid = $(this).attr('id'); // the id of the current disabled box
                if (checked) {
                    $('label[for='+lid+']').addClass('disabled');
                } else {
                    $('label[for='+lid+']').removeClass('disabled');
                }
            });
    });​
    

    and some css:

    .disabled {
        color: #888;
    }
    

    working example

    0 讨论(0)
提交回复
热议问题