I have HTML page which have multiple check boxes and individually they can be checked. I have button select
, so what I am suppose to do is. When I click on sel
This will definitely works.
$("#selectAll").click(function(){
var checked = !$(this).data('checked');
$('.btn-chk').prop('checked', checked);
$(this).data('checked', checked);
});
If you want to toggle the checkbox state, you can do like this
var chkd = true;
$('#selectAll').click(function(event) {
$(":checkbox").prop("checked", chkd);
chkd = !chkd;
});
Fiddle
inside the "click" function "this" is button and not a checkbox. and button property checked is underfined. "$('.btn-chk').each" - is loop on each element with class ".btn-chk", in your HTML is buttons and not an checkboxes.
in your context the "#selectAll" must be a checkbox and put class '.btn-chk' on your checkboxes
An simple way is like below:
$(function() {
$('#selectAll').click(function() {
$(':checkbox').prop('checked', !$(':checkbox').prop('checked'));
});
});
The Demo.
#selectAll
is a button, it doesn't have a checked
property, but one could emulate that with a data attribute instead.
Secondly, .btn-chk
isn't a checkbox either, so it can't be checked, you have to target the checkboxes
$(document).ready(function() {
$('#selectAll').click(function(event) {
var checked = !$(this).data('checked');
$('.btn-chk').next().prop('checked', checked);
$(this).data('checked', checked);
});
});
FIDDLE
Change your jQuery code to
$('#selectAll').click(function(event) { //on click
if($('.hidden').prop('checked') == false) { // check select status
$('.hidden').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.hidden').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
This will toggle between checked
and unchecked
of the checkboxes
when you click the button
.