I made a script in order to control master & slave checkboxes (automatic checking and unchecking).
Here is my JS :
$(document).ready(function() {
$('#myCheck').click(function() {
$('.myCheck').attr('checked', false);
});
$('.myCheck').click(function() {
if ($('.myCheck').is(':checked')) {
$('#myCheck').attr('checked', false);
} else {
$('#myCheck').attr('checked', true); // IT DOESN'T WORK, WHY ?
alert("Checkbox Master must be checked, but it's not!");
}
});
});
And here is my HTML :
<input type="checkbox" id="myCheck" checked="checked" /> Checkbox Master<br />
<input type="checkbox" class="myCheck" value="1" /> Checkbox Slave 1<br />
<input type="checkbox" class="myCheck" value="1" /> Checkbox Slave 2
Look at my simple JsFiddle to understand the problem.
EDIT 1 : Like Inser said, the problem happens with jQuery 1.9.2 and over. No more problem with jQuery 1.8.3. Strange...
EDIT 2 : Inser found the solution, use .prop('checked', true) instead .attr('checked', true). Look at the comments below...
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.
Select change eventCheck total options and total selected options if it is equal then set Select All checkbox checked otherwise unchecked it.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
Use prop method for new versions of jQuery:
$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);
http://jsfiddle.net/uQfMs/37/
You could try this.
$('#myCheck').click(function() {
var checkBoxes = $(this).siblings('input[type=checkbox]');
checkBoxes.prop('checked', $(this).is(':checked') ? true : false);
});
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