Selecting all checkboxes using jQuery

I just want to check all the checkboxes on the page if the user clicks the "Select All" button.

In body:

<button id="checkall">Select All</button> 

JQuery

 <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#checkall').click(function () { $("input[type=checkbox]").each( function() { $(this).attr('checked', true); }); }); </script> </head> 

And the flags are generated by a small amount of php:

 echo '<li>'; echo '<input type="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>'; echo '</li>'; 

Can someone tell me what I am doing wrong?

+4
source share
4 answers

You do not need every statement. Just select all the checkboxes and set the checked = true property.

 $(document).ready(function(){ $('#checkall').click(function () { $("input:checkbox").prop('checked', true); }); }); 

Note jQuery.prop () is a function added to 1.6 and above. If you are using jQuery version prior to 1.6, you will need the following.

 $(document).ready(function(){ $('#checkall').click(function () { $("input:checkbox").attr('checked','checked'); }); }); 
+10
source

Instead of selecting a flag with a tag name, it is better to assign it to a certain class and select it with the class name

  $(document).ready(function(){ $('#checkall').click(function () { $(".checkbox").each( function(i,chkbox) { $(chkbox).attr('checked', true); }); }); }); 

php code

  echo '<li>'; echo '<input type="checkbox" class="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>'; echo '</li>'; 
+1
source

You just skip }); for the operator .each(function(){} ! There has not been an error yet!

 $(document).ready(function () { $('#checkall').click(function () { $("input[type=checkbox]").each(function () { $(this).attr('checked', 'checked'); // or // $(this).attr('checked', true); }); // you missed this one!!! }); }); 
0
source

It will work, short and convenient code

 <script> $('#check_all').click(function () { $( this ).closest('form').find(':checkbox').prop( 'checked' , this.checked ? true : false ); }) </script> 
0
source

All Articles