How to select / deselect all checkboxes using jQuery?

In this jQuery tutorial, we are going to look at simple code snippet which can be very helpful to check / uncheck multiple checkboxes using a single checkbox. You may have noticed this functionality on websites like gmail.com or outlook.com which allows you to select all emails on the page using a single select all feature.

See Also: Get selected checkbox value using jquery

Before we move forward, let’s take a look at the image below to understand exactly what we are trying to achieve here.

How to select / deselect all checkboxes using jQuery?

How to select / deselect all checkboxes using jQuery?

As you can see, when we check the Select All checkbox all the other checkboxes will be checked automatically, similarly when we uncheck the Select All chechbox other checkboxes will be deselected.

HTML:

<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;
			});
		}
	})
});

Description:

When the user clicks the Select All option, the script detects whether the checkbox with ID selectAll is checked or not. Then, it will loop through all checkboxes with class chkbox and apply the status selectAll checkbox to each of them.

 

0 Comments

Leave a Comment.