I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,
<select onChange="javascript:doSomething();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Now, doSomething()
only gets triggered when the selection changes.
I want to trigger doSomething()
when the user selects any option, possibly the same one again.
I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.
So, is there a way to trigger a function on every select by the user?
Update:
The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
I had the same problem when I was creating a design a few months back. The solution I found was to use
.live("change", function())
in combination with.blur()
on the element you are using.If you wish to have it do something when the user simply clicks, instead of changing, just replace
change
withclick
.I assigned my dropdown an ID,
selected
, and used the following:I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.
http://api.jquery.com/live/
Edit: Use the
on
selector as opposed to.live
. See jQuery .on()you should try using
option:selected
Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:
This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.
The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.
The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.
Try:
Worked decent for me.
I needed something exactly the same. This is what worked for me:
Supports this:
Here is the simplest way:
Works both with mouse selection and keyboard Up/Down keys whes select is focused.