RyanScottLewis
RyanScottLewis

Reputation: 14016

Select Element onChange event is not firing?

I have a select element with an onChange event that does fire when I click the select box and select a new value within it. But, when I tab to the select box and press the up or down arrows to change the select box's value, the event does not fire.

I am using jQuery().change(function(){ ... }); to set the event

Upvotes: 4

Views: 17515

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23122

When you tab into a <select> element, the change event doesn't fire until you press the Enter key.

Upvotes: 2

Niklas
Niklas

Reputation: 30002

You can trigger the blur event on keyup on the select and then give back focus, which will trigger the change:

$('select').keyup(function(){
  $(this).blur().focus();
});

example: http://jsfiddle.net/niklasvh/XEg36/

Upvotes: 1

Robert
Robert

Reputation: 21388

As others have stated, the change event doesn't happen until the blur event. You'll need to monitor keyup as well to capture someone moving changing the values with the arrow keys.

Monitor keyup and change,

$('select').bind('change keyup', function() {
   // Handle
});

http://jsfiddle.net/robert/Je26w/

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

For an onChange() to fire the value must be changed and the input must be blur()-ed (focus moved elsewhere); which is why it fires in your first case, but not in the second.

The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Reference:

Upvotes: 1

Related Questions