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.
Yes. Add an onChange property to the first select, then use it to call a javascript function you have written elsewhere.
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.
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.
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); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With