dalgard
dalgard

Reputation: 43

Strange jQuery("checkbox").click().is(":checked") behavior

Can anyone explain why $(this).is(":checked") gives the opposite result when the checkbox is clicked with $("#test").click() than when clicked manually or with document.getElementById("test").click() ??

EDIT Requested behavior here - thanks:

http://jsfiddle.net/ub8Zk/4/

EDIT 2

This has been driving me nuts, but I finally realize -- in version 1.5.2 of jQuery the event handler for the change event is fired when click() method is called (like native js)!! Not so in previous versions.

Look here:

http://dl.dropbox.com/u/6996564/jquery_click_test/test-1.4.4.htm ... test-1.5.1.htm ... test-1.5.2.htm

Can someone help me report this bug??

Upvotes: 4

Views: 5776

Answers (4)

Martin Ongtangco
Martin Ongtangco

Reputation: 23535

$('input#someCheckbox').click(function() {
    if ($(this).is(':checked')) {
        // checked
    } else {
       // not checked
    };
});

Upvotes: 2

mozillanerd
mozillanerd

Reputation: 560

I don't see your code. click() binds according to documentation a handler to the mouse click event. You may also write:$('#foo').bind('click', function() { alert('User clicked on "foo."'); }); If you want to trigger use the trigger() function like so: $('foo').trigger('click') or document.getElementById('foo').checked = true; when using straight javascript.

Upvotes: -1

Bob Fincheimer
Bob Fincheimer

Reputation: 18076

The click event happens BEFORE the value changes, so it is getting the old value. The the default handler for click happens AFTER your click event and toggles the value. That is why it is getting the opposite value. I would think the document click function is doing something wierd (I would not trust it, I would trust jQuery).

Look at this fiddle: http://jsfiddle.net/ub8Zk/4/

Upvotes: 5

Hussein
Hussein

Reputation: 42818

Since you are using a checkbox input, you want is(':checked') not is(':selected')

Upvotes: 3

Related Questions