views:

31

answers:

3
    $('document').ready(function(){
        $('[name=mycheckbox]').live('click', function(){
            if($(this).is(':checked'))
            {
                alert('it is checked');
            }
            else
            {
                alert('it is not checked');
            }
        });

        $('[name=mycheckbox]').click();
    });

If the checkbox is checked and you click it, the alert box says, "it is not checked", but when the page runs and the click event is fired (with the checkbox checked), the alert box says, "it is checked". Why? Is the state of the checkbox not effected by the click event? Is it mousedown that changes the state?

+3  A: 

Instead of click you should use the change event here, like this:

$('[name=mycheckbox]').live('change', function(){

And invoke it with the same trigger, like this:

$('[name=mycheckbox]').change();

The click is separate from the change, if you want the event to fire when the check actually has finished changing, then you want change, not click. Alternately, if you want to toggle it from it's initial state still, do this:

$('[name=mycheckbox]').click().change();
Nick Craver
A: 

Instead of the live event (which I've found to be buggy at best) try binding a normal click even instead. I've done something similar which works fine with a .click event not .live("click",

I hope that helps :S

Dorjan
This isnt the problem at all. on a checkbox, click occurs before the change.
Jamiec
@Jamiec - What about his concern with `live()`. Is `live()` really buggy (aside from the main question)?
orokusaki
For me jamiec, it works fine, so I don't think that is the case.
Dorjan
And regarding what I said about live... it's silly things like right and left clicking triggering it and it seems to trigger on mouse downs instead of the full click. I'm speculating but this is from experience.
Dorjan
A: 

What is happening is quite subtle.

I have a button and checkbox linked to the following code:

$("#chkbx").click(function() {

    if ($(this).is(':checked')) {
        alert('checked');
    }
    else {
        alert('unchecked');
    }
});

$("#MyButton").click(function() {

    $("#chkbx").click();
});

When I click on the checkbox, everything is displayed as you would expect.

When I click on the button, the reverse is true.

What is happening, is that when you click on the checkbox, it is firing the default click event before executing your code, and thus you code is taking the status from the aftermath of the default click event.

When you call the click method directly on the element, it is actually calling your click function and then executing the default event.

I'm not why this should be. or if this is intentional, or a bug.

James Wiseman