Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run change event for select even when same option is reselected

Tags:

Basically, I have drop down menu that looks like this:

<select>   <option>0</option>   <option selected="selected">1</option>   <option>2</option>   <option>3</option> </select> 

I am trying to write a function that is fired even when you select the same option, i.e. even if the drop-down is opened and re-select the selected option, I want it to execute the function.

like image 227
Spencer Avatar asked Oct 12 '11 15:10

Spencer


People also ask

Can I use OnChange in select tag?

Yes. Add an onChange property to the first select, then use it to call a javascript function you have written elsewhere.

What triggers OnChange event?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

What is OnChange select?

Event Handling With the Select Element The onChange attribute of <select> lets you dynamically change something on screen, without reloading the page. For example, your can use it to display a particular image, depending on the user's selection.


2 Answers

If you mean selecting with the mouse, you can use mouseup. However, it will fire when the select box is being opened as well, so you'll need to keep track of the amount of times it was fired (even: select is being opened, odd: select is being closed): http://jsfiddle.net/T4yUm/2/.

$("select").mouseup(function() {     var open = $(this).data("isopen");      if(open) {         alert(1);     }      $(this).data("isopen", !open); }); 
like image 73
pimvdb Avatar answered Sep 21 '22 05:09

pimvdb


pimvdb's answer was a big help for me but I added a couple of extra bits to deal with keyboard activation and navigation away from the select:

$('select').mouseup(... as in pimvdb... )   .blur(function() {      $(this).data('isopen', false);   }).keyup(function(ev) {      if (ev.keyCode == 13)         alert(1);   }); 

The blur handler deals with navigating away from the select while the dropdown is open, the keyup handler deals with when you change the select's value with the keyboard. The behaviour is then that the user is only considered to have finally selected the value when they click return to navigate away. If you want a different behaviour with the keyboard that shouldn't be hard to do.

like image 34
James Ellis-Jones Avatar answered Sep 21 '22 05:09

James Ellis-Jones