Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and uncheck all checkboxes with jquery

I am using this script to check and uncheck all checkboxes:

$('#checkall').click(function () {
    var checked = $(this).data('checked');
    $('.chkall').find(':checkbox').attr('checked', !checked);
    $(this).data('checked', !checked);
});

It works great, but as soon as I uncheck several checked checkboxes after "check all" and then hit "uncheck all" and "check all" again, those previously unchecked checkboxes are not checked again. Help would be great! Thank you very much!

like image 218
RobinAlexander Avatar asked Dec 07 '16 10:12

RobinAlexander


2 Answers

This might be the correct way..

Use prop instead of attr and group the checkbox list inside a div, just for organizing purposes. Also use the checked as it is, don't negate it.

$(document).ready(function() {
  $('#checkall').click(function() {
    var checked = $(this).prop('checked');
    $('#checkboxes').find('input:checkbox').prop('checked', checked);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkall" />
<label for="checkall">check / uncheck all</label>
<br/>
<br/>
<div id="checkboxes">
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />

</div>
like image 53
Jones Joseph Avatar answered Oct 16 '22 13:10

Jones Joseph


$('#checkall').click(function(){
    var d = $(this).data(); // access the data object of the button
    $(':checkbox').prop('checked', !d.checked); // set all checkboxes 'checked' property using '.prop()'
    d.checked = !d.checked; // set the new 'checked' opposite value to the button's data object
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='checkall' data-checked='false'>check/uncheck all</button>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>
<input type=checkbox>

I guessed what your HTML looks like, in terms of the triggering button, but what I don't know is how you initially set the data on it. hope this is the way you have it coded. if not, please tell.

like image 21
vsync Avatar answered Oct 16 '22 12:10

vsync