Last Updated: January 19, 2022
·
55.12K
· tmaster

Check all the checkboxes by clicking one button

So the example html is like below:

<button type="button" id='check_all'>Check All</button>`

<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
<input type="checkbox" name="vehicle" value="Motorbike">I have a Motorbike 

We can check or uncheck them all using:

$('#check_all').click(function() {
    $('input[name=vehicle]').prop('checked', true);
});

$('#check_all').click(function() {
    $('input[name=vehicle]').prop('checked', false);
});

Related protips:

jQuery: When to use $(document).ready() and when $(window).load()

4 Responses
Add your response

Here's more universal version:

/**
 * Un/Select multiple checkboxes using one checkbox
 * @param  {jQuery selector} $list List of checkboxes
 * @return {object}
 */
$.fn.checkboxMaster = function(list) {

    return this.on('click', function() {
        $(list).prop('checked', $(this).prop('checked'));
    });

}

Usage:

$('#check_all').checkboxMaster('input[name=vehicle]');
over 1 year ago ·

@idered That's a pretty neat function, but my example uses a radio button instead of a checkbox. How can I modify your function to suit the example? I tried to set checked property on the button in the html <button type="button" id='check_all' checked>Check All</button>, but it did not work. I then tried to use jQuery to set it $('#check_all').prop('checked', true);which actually works, but it wont achieve the same effect as your original function, because clicking the button won't change the checked property from true to false. So any suggestions?

over 1 year ago ·

@idered workaroud seems to work with any control that contains 'Checked' property.

over 1 year ago ·

@tmaster, @felipekm How about this?

$.fn.checkboxMaster = function(list) {

    return this.on('click', function() {

        var isChecked = $(list).first().prop('checked');

        $(list).prop('checked', ! isChecked );

    });

}
over 1 year ago ·