jquery select all checkboxes

前端 未结 19 2634
情书的邮戳
情书的邮戳 2020-12-13 12:36

I have a series of checkboxes that are loaded 100 at a time via ajax.

I need this jquery to allow me to have a button when pushed check all on screen. If more are lo

19条回答
  •  有刺的猬
    2020-12-13 13:27

    Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:

    (function($) {
        // Checkbox toggle function for selecting all checkboxes on the page
        $.fn.toggleCheckboxes = function() {
            // Get all checkbox elements
            checkboxes = $(':checkbox').not(this);
    
            // Check if the checkboxes are checked/unchecked and if so uncheck/check them
            if(this.is(':checked')) {
                checkboxes.prop('checked', true);
            } else {
                checkboxes.prop('checked', false);
            }
        }
    }(jQuery));
    

    Then simply call the function on your checkbox or button element:

    // Check all checkboxes
    $('.check-all').change(function() {
        $(this).toggleCheckboxes();
    });
    

    As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():

    // Check all checkboxes
    $(document).on('change', '.check-all', function() {
        $(this).toggleCheckboxes();
    });
    

提交回复
热议问题