Jquery focus() with checkboxes problem

DavidWainwright picture DavidWainwright · Aug 19, 2011 · Viewed 11.1k times · Source

We use a custom jquery plugin to handle our help pop-ups when users focus on input fields. However I've stumbled upon an odd problem. The plugin uses the following code to trigger the help popup:

$(this).focus(function(){
    // Show popup help panel here
});

However, if this code is applied to an input where type="checkbox", the help popup is displayed, but the checkbox value quickly negates itself, therefore appearing not to have changed from ticked to unticked or vice-versa. This happens in IE9 and FF6 (not tried it in other browsers). I tried this very simple code just to make sure I wasn't going insane, and the issue still occurred:

... In html:

<input id="test" type="checkbox" checked="checked" />

... In head - javascript

$('#test').focus(function(){
    alert("help!");
});

The alert is displayed, but the checkbox value isn't changed (or was changed but then changed back, as I think is happening).

Can anyone shed any light on this.

Answer

Adam Terlson picture Adam Terlson · Aug 19, 2011

Why bind on 'focus' for a checkbox?

That doesn't make much sense to me as 'focus' is primarily for textboxes or textareas. I'd use .click or .change instead, I'd suspect you'll have better luck.

Did some testing on a jsfiddle (http://jsfiddle.net/65CRb/1) and binding focus doesn't even work at all in Chrome. I'd suspect there's some weird eventing going on in IE/FF that isn't propagating to the actual control itself when you focus.