Because the click
event is different from the change
event, which is where the element changes. When the <div>
does a .click()
is triggers the click
event which hasn't yet changed the state of the checkbox so when it checks it, it's in the previous state.
When you click directly on the <input>
, you've already changed the state, even if the change
event fires 2nd in order, the main point is the checkboxes checked
status has changed, before the click
handler is checking for it, so the state is current.
If you want accurate state information look for and trigger the change
event instead, like this:
$(function() {
$('input').change(function() {
$("span").append("<br />" + (this.checked ? "Checked" : "Uncecked"));
});
$('div').click(function() {
$('input').click().change();
});
});
You can give it a try here, on the off-chance this isn't a behavior question and you're wanting an external clickable area, this is how I'd do it (via a <label>
wrapping the input).