X
    Categories: Jquery

select all checkbox in jquery

Select all checkbox in jquery

By using jquery we can check all check boxes as well as deselect all check boxes like gmail. Why we need to keep select and deselect all checkboxes? When your application has more than 1000 unwanted names you cannot go and delete the record for each time, Instead of that you can check all the records and delete them in single request. Jquery providing simple and easy way to do this.

 

HTML Code

<ul class="chk-container">

<li><input type="checkbox" id="selecctall"/> Select All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" >
Name = "check[]" => check[] mention the check is a check box name which is declared as array. So all the check box values are stored in array() in the name of check.

Jquery Code.

Below of my will explain how to check all the checkboxes and checked checkbox values.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#selecctall').click(function(event) {  //on click 
        if(this.checked) { // check select status
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"               
            });
        }else{
            $('.checkbox1').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                       
            }); 		
        }
		var chkArray = [];
		$("input[name='check[]']:checked").map(function() {
			chkArray.push(this.value);
		}).get();
		var selected;
		selected = chkArray.join(',') + ",";
		if(selected.length > 1){
			alert(selected);
		} else { alert('You have deselected all values'); }		
		
    });
    
});
</script>

 

Thanks!. If you like this article don't forget to comment and share.

 

Marimuthu:

View Comments