marco-fiset marco-fiset - 1 year ago 84
jQuery Question

jQuery change event fired twice when giving focus to another control inside the change callback

A weird bug caused me a lot of headaches recently, and I've been able to dumb it down to the simplest form possible. See this fiddle :

<input type="text" id="foo" placeholder="Change me!"><br>
<input type="text" id="bar" size="30" placeholder="Dummy control to switch focus">

$('#foo').change(function() {

Basically, when you change the first textbox and use the mouse to click elsewhere in the document, the change event fires, as usual. However, if you change the value, and hit the enter key to trigger the change, the event fires twice.

I've noticed the bug is only with Chrome. Firefox does not trigger the event twice, and IE does not even support the enter key to trigger change on an input.

I guess that happens because of the focus switching inside the event callback. Is there any way around this?

Answer Source

The focus() on other control in your change eventhandler call the change event in chrome because it unfocus "blur" your current control if the value is different.

This bug is not new, you can take a look at this bug ticket on jQuery :

You can work around this by disabling the change eventhandler before to remove the focus on your control. Here a little exemple of what I want to say:


function changeHandler() {
    $(this).off('change').blur().on('change', changeHandler);