4

Possible Duplicate:
In jQuery, why does programmatically triggering ‘click()’ on a checkbox not immediately check it?

Update: This only applies to jQuery 1.8 and below. This was fixed in jQuery 1.9.

I have this checkbox.

<input type="checkbox" id="wtf">

And this event handler:

$('#wtf').click(function(ev) { ev.preventDefault(); alert(this.checked); });

When I click the checkbox, I first see the checkmark appear, then I see the alert "true", then I see the checkmark disappear.

But when I call $('#wtf').click(), I don't see any checkmark appear, and I see the alert "false".

Why is the behavior different when the click is manual vs when the click is programmatic?

I'm using Google Chrome, if that makes a difference.

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145

3 Answers3

2

The reason is that calling the .click() function is only firing a function. It is actually a call to the function that fires when that button is clicked; it is not actually changing the state of the checkbox. However when you manually click it you are changing the state, which then in turn calls the function.

PCasagrande
  • 5,302
  • 3
  • 27
  • 36
  • Actually, on second thought it doesn't really make sense. See: http://jsfiddle.net/8fuEJ/. The programmatic 'click()' event *does* change the state of the chcekbox. It just does it in a different order than manually clicking on it. – Ben Lee Oct 06 '11 at 18:23
  • It does so after the function is being called. This is in large part due to the ability to cancel the click or any number of other things the javascript could do. – PCasagrande Oct 06 '11 at 18:24
  • What you can't see in the background is that javascript is actually changing the state of the checkbox. – PCasagrande Oct 06 '11 at 18:25
  • Ok, saw your answer in my other question and it makes sense now. Thanks again! – Ben Lee Oct 06 '11 at 18:26
1

I think it has to do with the Checkbox control itself. The event you are firing is onchange rather than a click. Since the Checkbox can be checked or unchecked. It cannot be seen merely as a button. I think the same issue can be found with radio buttons.

George
  • 1,526
  • 1
  • 10
  • 2
0

Correct and correct. Checkboxes have state of either checked or unchecked. The click event is a generic event that can be applied to just about any element in an HTML page. If you want to test value or conditionally fire a function, check for $('wtf').is(':checked') first.

Watermark Studios
  • 1,173
  • 1
  • 10
  • 24