I have the following html code:
<input type="checkbox" id="ckbCheckAll" /> <p id="checkBoxes"> <input type="checkbox" class="checkBoxClass" id="Checkbox1" /> <br /> <input type="checkbox" class="checkBoxClass" id="Checkbox2" /> <br /> <input type="checkbox" class="checkBoxClass" id="Checkbox3" /> <br /> <input type="checkbox" class="checkBoxClass" id="Checkbox4" /> <br /> <input type="checkbox" class="checkBoxClass" id="Checkbox5" /> <br /> </p>
When user checks ckbCheckAll
all checkboxes must be checked. Also I have following jquery code:
$(document).ready(function () { $("#ckbCheckAll").click(function () { $(".checkBoxClass").attr('checked', this.checked); }); });
When I see my page in the browser I get the following result: In the first click on ckbCheckAll
all checkboxes were checked (which is correct). In the second click on ckbCheckAll
all checkboxes were unchecked (which is correct). But in 3rd attempt nothing happened! also in 4th attempt nothing happened and so on.
Where is the problem?
In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.
click(function(){ $(':checkbox'). prop("checked", true); alert("1"); }); $('#deselectChb'). click(function(){ $(':checkbox'). prop("checked", false); alert("2"); });
Use prop
$(".checkBoxClass").prop('checked', true);
or to uncheck:
$(".checkBoxClass").prop('checked', false);
http://jsfiddle.net/sVQwA/
$("#ckbCheckAll").click(function () { $(".checkBoxClass").prop('checked', $(this).prop('checked')); });
Updated JSFiddle Link: http://jsfiddle.net/sVQwA/1/
Here is a simple way to do this :
Html :
<input type="checkbox" id="selectall" class="css-checkbox " name="selectall"/>Selectall<br> <input type="checkbox" class="checkboxall" value="checkbox1"/>checkbox1<br> <input type="checkbox" class="checkboxall" value="checkbox2"/>checkbox2<br> <input type="checkbox" class="checkboxall" value="checkbox3"/>checkbox3<br>
jquery :
$(document).ready(function(){ $("#selectall").click(function(){ if(this.checked){ $('.checkboxall').each(function(){ $(".checkboxall").prop('checked', true); }) }else{ $('.checkboxall').each(function(){ $(".checkboxall").prop('checked', false); }) } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With