Here is my HTML:
<input class='user_roles' id="chk" type=checkbox />
<input id="btn_on" type="button" value="on" />
<input id="btn_off" type="button" value="off" />
And my jQuery:
$('#chk').click(function() {
if($(this).prop("checked") === true) {
alert ("checked");
}
else{
alert ("not checked");
}
});
$("[id$=btn_on]").click(function () {
$('#chk').click();
});
$("[id$=btn_off]").click(function () {
$('#chk').click();
});
A working example is here.
When the checkbox is clicked with the mouse it is checked straight away - that is, the alert displays "checked". However when one of the buttons is clicked, which indirectly call the click method on the checkbox, the checkbox is not clicked until after the click code has been run.
To test this, click the check box a couple of times with the mouse and you will see the alerts "checked" and "not checked" respectively. Click "On" and you will see the alert "not checked", and then the checkbox becomes checked. If you then click "Off" you will see "checked" followed by the checkbox unchecking itself.
What is the reason for this behaviour? How can I ensure that the checkbox "checking" happens before the click listener code is called, as per the mouse behaviour?
if its just a question about getting it to work, use .change()
instead of .click()
on your check box, if its about why it does what it does i have no idea sorry
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