Hello. There are checkboxes that are output through a loop.

<input type="checkbox" id="subs<?=$item['id']?>" name="subs[]" value="<?=$item['email']?>" checked=""> 

By default, they are all checked. Made a button and I want that when you click on the button all checkboxes are removed or set based on the primary state? I can not understand how to implement with all the checkbox

  • Not a duplicate. There to remove, and then invert. - Qwertiy
  • @duddeniska added another answer without the each cycle. So that you knew) - Alexey Shimansky
  • @Qwertiy re-opening) - Alexey Shimansky
  • @ Alexey Shimansky, better say: without explicitly calling each :) - Grundy
  • @Grundy go for a walk) - Alexey Shimansky

1 answer 1

 $('input[type=button]').on('click', function(){ $('input[type=checkbox]').each(function() { var checked = $(this).prop('checked'); $(this).prop('checked', !checked); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="checkbox" checked /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" checked /> <input type="checkbox" checked /> <input type="button" value="clickme" /> 

Run the elements. We look at their minted attribute checked . Take it and change it to the opposite.


UPD. They say each is optional. So you can even write like this:

 $('input[type=button]').on('click', function(){ $('input[type=checkbox]').prop( "checked", function(i, prop) { return !prop; }); });