views:

315

answers:

3

When I bind a function to a checkbox element like:

$("#myCheckbox").click( function() {
    alert($(this).is(":checked"));
});

The checkbox changes it checked attribute before the event is triggered, it's it normal behavior, thus giving and inverse result.

However, when I do:

$("#myCheckbox").click();

The checkbox changes it checked attribute after the event is triggered.

My question is, is there a way to trigger the click event from jquery like a normal click would do (first scenario)?

PS: I've already tried with trigger('click');

+3  A: 

I would think you should use the "change" handler instead:

$('#myCheckbox').change(function () {
    if ($(this).attr("checked")) {
        // checked
        return;
    }
    // not checked
});
tcurdt
I've tried that, "$(#myCheckbox).click()" unchecks/checks the box but the change function is never triggered. I've also tried changing the 'checked' attribute instead of calling click() and even setting the 'change' function to 'live'.
Ben
@Ben - You have to trigger it in a different way to get this to run, see my answer for the trigger statement.
Nick Craver
@Nick Thanks, I will accept tcurdt answer as he was the first to come out with the solution. Silly me i didn't triggered the 'change' method.
Ben
+1  A: 

Well, to match the first scenario, this is something I've come up with.

http://jsbin.com/uwupa/edit

Essentially, instead of binding the "click" event, you bind the "change" event with the alert.

Then, when you trigger the event, first you trigger click, then trigger change.

RussellUresti
+1  A: 

There is a work-around that works in jQuery 1.3.2 and 1.4.2:

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');​​​​​​​​​​​​​

But I agree, this behavior seems buggy compared to the native event.

Nick Craver