Consider the following code:
HTML:
<input type='checkbox' />
<div>Click here</div>
JS:
$(function() {
$('input').click(function() {
document.write($(this).is(':checked') ? "checked" : "unckecked");
});
$('div').click(function() {
$('input').click();
});
});
When the checkbox is clicked, the output is checked, but if “Click here” is clicked the output is unckecked. Why is that?
Because the
clickevent is different from thechangeevent, which is where the element changes. When the<div>does a.click()is triggers theclickevent 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 thechangeevent fires 2nd in order, the main point is the checkboxescheckedstatus has changed, before theclickhandler is checking for it, so the state is current.If you want accurate state information look for and trigger the
changeevent instead, like this: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).