Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 : http://jsfiddle.net/PgAAb/

<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() {
    console.log('Changed!');
    $('#bar').focus();
});

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?

like image 571
marco-fiset Avatar asked Oct 07 '13 16:10

marco-fiset


1 Answers

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 : http://bugs.jquery.com/ticket/9335

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:

$('#foo').change(changeHandler);

function changeHandler() {
    console.log('Changed!');
    $(this).off('change').blur().on('change', changeHandler);
    $('#bar').focus();
}
like image 126
EmeraldCoder Avatar answered Sep 24 '22 15:09

EmeraldCoder