Thursday, December 11, 2014

How to Select and Deselect All Checkboxes Using jQuery

Here, is the simple code snippet which can be very useful to check and unchecked multiple checkboxes using a single checkbox.


So, first of all, let's take a look at the image below to get an exact idea about it. When we check the Select All checkbox all the other checkboxes will be checked automatically, similarly when we uncheck the Select All checkbox other checkboxes will be deselected.


Get the code below to execute this task. 

HTML Code:

<ul>
<li><input type="checkbox" id="selectAll"> Select All</li>
<li><input type="checkbox" name="item[]" value="value1" class="chkbox">Item 1</li>
<li><input type="checkbox" name="item[]" value="value2" class="chkbox">Item 2</li>
<li><input type="checkbox" name="item[]" value="value3" class="chkbox">Item 3</li>
<li><input type="checkbox" name="item[]" value="value4" class="chkbox">Item 4</li>
<li><input type="checkbox" name="item[]" value="value5" class="chkbox">Item 5</li>
</ul>

jQuery:

$(document).ready(function(){
$('#selectAll').on('click',function(){
if ($(this).is(':checked')) {
$('.chkbox').each(function(){
this.checked = true;
});
}else{
$('.chkbox').each(function(){
this.checked = false;
});
}
})
});

0 comments:

Post a Comment