views:

112

answers:

1

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?

+12  A: 

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). ​

Nick Craver
@Nick: you're probably right. I misunderstood because instead of fixing his broken demo, I just answered the question how I interpreted it :-P +1.
Andy E
Thanks a lot, Nick !
Misha Moroshko
@Misha - Welcome, @Andy - Thanks :) I think yours is a good addendum to the question for others finding it, looking for that route...undelete it and you'd get a +1 from me at least.
Nick Craver