问题
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?
回答1:
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);
}
});
回答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);
}
});
来源:https://stackoverflow.com/questions/18266369/how-can-i-check-multiple-check-boxes-in-jquery