How To Check And Uncheck All Checkboxes In An Html Table With Checking/unchecking One Check Box?
I have a table, with rows, every row has a check box, and there is a main check box at the thead. My code:
Solution 1:
Working Demo http://jsfiddle.net/xYAfj/2/
$('#allcb').change(function(){
if($(this).prop('checked')){
$('tbody tr td input[type="checkbox"]').each(function(){
$(this).prop('checked', true);
});
}else{
$('tbody tr td input[type="checkbox"]').each(function(){
$(this).prop('checked', false);
});
}
});
Shorter Code
Working Demo http://jsfiddle.net/cse_tushar/4tss8/
$('#allcb').change(function () {
$('tbody tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
Solution 2:
$(function(){
$("#allcb").click(function() {
var chkBoxes = $("input[id^=cb]");
chkBoxes.prop("checked", !chkBoxes.prop("checked"));
});
});
Solution 3:
I made a little modification on your HTML code by changing the names of the checkboxes in the table body from cbn to cb[] (better for server operations). I also took in account the fact that the main checkbox state can be changed by clicking on another checkbox: if the user manually selects all the other checkboxes, then the main checkbox should reflect it; also, if the user unchecks a row after clicking the main checkbox to check all the others, then the main checkbox should get unchecked.
You can see it working there : https://jsfiddle.net/h6tgj02p/
<tableborder="1"><thead><tr><th><inputtype="checkbox"id="allcb"name="allcb"/></th><th>values</th></tr></thead><tbody><tr><td><inputtype="checkbox"id="cb1"name="cb[]"/></td><td>value1</td></tr><tr><td><inputtype="checkbox"id="cb2"name="cb[]"/></td><td>value2</td></tr><tr><td><inputtype="checkbox"id="cb3"name="cb[]"/></td><td>value3</td></tr></tbody></table><scripttype="text/javascript">
$(document).ready(function() {
/*
* Click on select all checkbox
*/
$('#allcb').click(function(e) {
$('[name="cb[]"]').prop('checked', this.checked);
});
/*
* Click on another checkbox can affect the select all checkbox
*/
$('[name="cb[]"]').click(function(e) {
if ($('[name="cb[]"]:checked').length == $('[name="cb[]"]').length || !this.checked)
$('#allcb').prop('checked', this.checked);
});
});
</script>
Post a Comment for "How To Check And Uncheck All Checkboxes In An Html Table With Checking/unchecking One Check Box?"