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!
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>
$('#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With