As the OP requires to check uncheck all checkboxes on the basis of another checkbox id=全選
.
The solution that @j08691 is provided above is good but it lacks one thing and that is, the solution doesn't uncheck the id=全選
checkbox when any other checkbox in the list goes unchecked.
So I propose a solution that checks/unchecks all the checkboxes on the basis of id=全選
checkbox and if any other checkbox is unchecked then checkbox id=全選
goes unchecked. And if user manually clicks on all the other check boxes then check box id=全選
should also be checked to reflect the relationship.
OP using the same id for multiple checkboxes which is against the rules of DOM. Element IDs should be unique within the entire document.
So the following code covers all the aspects of this kind of scenario.
HTML
<table>
<tr>
<td>
<input type="checkbox" name="checkAll" id="checkAll">全選 (ALL)
<input type="checkbox" name="book" id="book_1" value="book1">book1
<input type="checkbox" name="book" id="book_2" value="book2">book2
<input type="checkbox" name="book" id="book_3" value="book3">book3
<input type="checkbox" name="book" id="book_4" value="book4">book4
<input type="checkbox" name="book" id="book_5" value="book5">book5
</td>
</tr>
</table>
JQuery
$(document).ready(function() {
$('#checkAll').click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
$("[id*=book_]").change(function () {
if ($('input[id*=book_][type=checkbox]:checked').length == $('input[id*=book_][type=checkbox]').length) {
$('#checkAll').prop('checked', true);
} else {
$('#checkAll').prop('checked', false);
}
});
});
Description of attribute selector [name*="value"]
Selects elements that have the specified attribute with a value containing a given substring.
So $('#checkAll')
returns me the parent checkbox only, on which I check/uncheck all checkboxes.
And $('[id$=book_]')
returns me all the checkbox except the parent(全選) checkbox. Then on the basis of parent checkbox I check/uncheck all the other checkboxes.
I also checks the length of the checkboxes other then parent(全選) checkbox, If all the other checkboxes are check then I check the parent(全選) checkbox. So this is the way to cross check all possible condition and never misses any scenario.
Demo working JSFiddle here.