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!
If you really need this to work like this, I would do this (to ensure it works by keyboard and mouse)
Unfortunately the onclick will run multiple times (e.g. on onpening the select... and on selection/close) and the onkeypress may fire when nothing changes...
You can use onChange: http://www.w3schools.com/TAGS/tag_Select.asp
Copied from http://www.faqs.org/docs/htmltut/forms/_SELECT_onChange.html onChange designates a JavaScript to run when the user chooses one of the options. This means that an action is initiated immediately when the user chooses an item, not when a "submit" button is pressed.
I found out this solution .
set the selectedIndex of select element to 0 initially
call this method onChange event
To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.
Like others have said, specify a negative
selectedIndex
on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.Standard JS/HTML:
jQuery Plugin:
You can see a working demo here.
Actually, the onclick events will NOT fire when the user uses the keyboard to change the selection in the select control. You might have to use a combination of onChange and onClick to get the behavior you're looking for.
Try this: