Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the change event be fired when text field's value is changed both manually and programmatically?

I have a jQuery UI Autocomplete text field with a remote datasource. The autocomplete's select event does three things:

  1. Updates the text field's value with the one selected from the autocomplete list
  2. Makes an AJAX call to load some more data into the page
  3. Moves focus to another text field (created in the previous step)

The text field also has a change event that removes the data loaded in step 2 above and triggers the autocomplete's search event.

This works perfectly in IE (tested with versions 9 and 10), but not in Firefox. When I make a selection from the autocomplete list, the extra data is never shown (though analysing the network traffic shows that the AJAX call is being made) and the autocomplete's search event is triggered. I managed to track the problem down to Firefox triggering the text field's change event after step 3 above, apparently because I typed something into the text field to trigger the autocomplete list, and despite the fact that the text field was later updated programmatically.

Quick example: http://jsfiddle.net/2umrJ/1
(For the sake of brevity that example just uses a keyup event on the text field.)

Output in IE10:

input1.focus() triggered
input1.blur() triggered
input2.focus() triggered

Output in Firefox 20:

input1.focus() triggered
input1.change() triggered
input1.blur() triggered
input2.focus() triggered

As can be seen, Firefox fires the change event while IE doesn't. Now I know that by default (i.e. without any extra code) the change event is only triggered when the value was changed manually, but what is the correct behaviour when the value is changed both manually and programmatically without the field losing focus in between?

Also, more importantly for my particular case, if Firefox's behaviour is correct (or at least not incorrect), what's the best way to prevent it? I don't want the change event to be triggered when focus is being changed programmatically, after I selected something from the autocomplete list.

like image 942
Indrek Avatar asked Oct 22 '22 13:10

Indrek


1 Answers

To prevent the change event from triggering in firefox, I would have something in your logic that sets a variable stating it's being changed programatically and in the change event logic, you should check that variable, don't execute the change logic if it's programatically triggered, and reset the variable before exiting.

like image 59
Zach Avatar answered Nov 03 '22 22:11

Zach