I have a table with a checkbox at the start of each row. Each Checkbox has the ID of #tablecheckbox. The table header row has a check icon which should check all boxed in the table. How can I do this with jQuery?
Asked
Active
Viewed 4,372 times
18
-
What have you already tried? – Andrey Shchekin Aug 16 '13 at 05:29
-
5^^ and ID's should be unique. – dc5 Aug 16 '13 at 05:29
-
Make your ids a class, then follow this link: http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery-or-javascript?rq=1 – bfavaretto Aug 16 '13 at 05:31
-
instead of using id try to use name attriubute it can help to check all check boxs. – tamilmani Aug 16 '13 at 05:32
-
Can you please show the code for your table (at least the header and a few body rows)? – rink.attendant.6 Aug 16 '13 at 05:38
-
A simpler way of achieveing the same has been suggested here: http://stackoverflow.com/questions/15979318/how-do-i-check-multiple-checkboxes-with-jquery-without-giving-each-an-id – ds345 Aug 16 '13 at 05:57
2 Answers
6
Here head_checkbox is id of top header and person class is all row checkbox
$('#head_checkbox').on('change', function () {
if ($(this).is(':checked')) {
$('.person').attr('checked', true);
} else {
$('.person').attr('checked', false);
}
});
$('.person').click(function () {
var total_length = $('.person').length;
var total_checked_length = $('.person:checked').length;
if (total_length == total_checked_length) {
$('#head_checkbox').attr('checked', true);
} else {
$('#head_checkbox').attr('checked', false);
}
});

Jay Hardia
- 746
- 6
- 16
-
1
-
I used to set `document.getElementById("head_checkbox").checked` attribute. Your approach seems more clean. Thanks. – Aryan Firouzian Jan 16 '19 at 09:48
2
$('#head_checkbox').click(function () {
if ($(this).is(':checked')) {
$('.person').attr('checked', true);
} else {
$('.person').attr('checked', false);
}
});
$('.person').click(function () {
if ($('.person').length == $('.person:checked').length) {
$('#head_checkbox').attr('checked', true);
} else {
$('#head_checkbox').attr('checked', false);
}
});

Kanishka Panamaldeniya
- 17,302
- 31
- 123
- 193