You are currently viewing How to Select/Deselect all checkbox using jQuery/javaScript

How to Select/Deselect all checkbox using jQuery/javaScript

Checkbox is a html element where you can select multiple element of your choice. Sometimes it’s required to select all checkbox on single click and remove vice versa. If you want to select all checkbox by clicking “Select All” then follow below code.

jQuery

When user click on “Select All” checkbox, the code simply iterate through all checkbox input fields with class class=”checkbox” and applies the checked status (true or false) of clicked checkbox which has id id=”all_element”. We also need to make sure, when user decides to un-check one of the checkbox from the list, the “Select All” checkbox should also be automatically unchecked. The jQuery code is

//select all checkboxes
$("#all_element").change(function(){  //"select all" change 
	var status = this.checked; // "select all" checked status
	$('.checkbox').each(function(){ //iterate all listed checkbox items
		this.checked = status; //change ".checkbox" checked status
	});
});

$('.checkbox').change(function(){ //".checkbox" change 
	//uncheck "select all", if one of the listed checkbox item is unchecked
	if(this.checked == false){ //if this item is unchecked
		$("#all_element")[0].checked = false; //change "select all" checked status to false
	}
	
	//check "select all" if all checkbox items are checked
	if ($('.checkbox:checked').length == $('.checkbox').length ){ 
		$("#all_element")[0].checked = true; //change "select all" checked status to true
	}
});

JavaScript

var all_element = document.getElementById("all_element"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items

//select all checkboxes
select_all.addEventListener("change", function(e){
	for (i = 0; i < checkboxes.length; i++) { 
	     checkboxes[i].checked = all_element.checked;
	}
});


for (var i = 0; i < checkboxes.length; i++) {
	checkboxes[i].addEventListener('change', function(e){ //".checkbox" change 
	//uncheck "select all", if one of the listed checkbox item is unchecked
	if(this.checked == false){
		all_element.checked = false;
	}
	//check "select all" if all checkbox items are checked
	if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
		all_element.checked = true;
	}
   });
}

Example

HTML

<input type="checkbox" id="select_all"/> Select All Color
<input class="checkbox" type="checkbox" name="check[]" value="Red">Red
<input class="checkbox" type="checkbox" name="check[]" value="Green">Green
<input class="checkbox" type="checkbox" name="check[]" value="Blue">Blue
<input class="checkbox" type="checkbox" name="check[]" value="Yellow">Yellow
Select All Color
Red
Green
Blue
Yellow

Leave a Reply