Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between clicking a checkbox and calling its '.click()' function?

Tags:

html

jquery

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?

like image 682
Misha Moroshko Avatar asked Sep 10 '10 09:09

Misha Moroshko


1 Answers

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

like image 126
Nick Craver Avatar answered Oct 27 '22 01:10

Nick Craver