Check all other checkboxes when one is checked

后端 未结 10 803
感情败类
感情败类 2020-12-09 23:11

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them look

10条回答
  •  鱼传尺愫
    2020-12-09 23:46

    Thanks to @Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.

    FIDDLE

    HTML

    
    
    




    SCRIPT

    $('.selectall').click(function() {
        if ($(this).is(':checked')) {
            $('input:checkbox').prop('checked', true);
        } else {
            $('input:checkbox').prop('checked', false);
        }
    });
    

    And now add this to manage the master checkbox as well...

    $("input[type='checkbox'].justone").change(function(){
        var a = $("input[type='checkbox'].justone");
        if(a.length == a.filter(":checked").length){
            $('.selectall').prop('checked', true);
        }
        else {
            $('.selectall').prop('checked', false);
        }
    });
    

提交回复
热议问题