zvmpcq
Last Updated: February 25, 2016
·
19.03K
· tmaster
5be895c8f22353c868cd161bbac44730

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);
});
Say Thanks
Respond

4 Responses
Add your response

4378
190043 533696520020804 1840519452 n

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 ·
4382
5be895c8f22353c868cd161bbac44730

@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 ·
4387
Moshed 2015 3 17 14.32.26

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

over 1 year ago ·
4388
190043 533696520020804 1840519452 n

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