I'm gathering that you just want the dropdown to fire anytime a selection is made. If so, check out the answer to Fire event each time a DropDownList item is selected with jQuery.
See my updated answer below:
<strike>You can use this small extension:</strike>
<!-- language: lang-js -->
<pre><code><strike>$.fn.selected = function(fn) {
return this.each(function() {
var clicknum = 0;
$(this).click(function() {
clicknum++;
if (clicknum == 2) {
clicknum = 0;
fn(this);
}
});
});
}
</strike></code></pre>
Then call like this:
$(".lead-action").selected(function(e) {
alert('You selected ' + $(e).val());
});
#Update:
I'm actually rather unhappy with the original script. It will break in a lot of situations, and any solution that relies on checking the click count twice will be very fickle.
###Some scenarios to consider:
- If you click on, then off, then back on, it will count both clicks and fire.
- In firefox, you can open the menu with a single mouse click and drag to the chosen option without ever lifting up your mouse.
- If you use any combination of keyboard strokes you are likely to get the click counter out of sync or miss the change event altogether.
- You can open the dropdown with <kbd>Alt</kbd>+<kbd>ā</kbd> (or the <kbd>Spacebar</kbd> in Chrome and Opera).
- When the dropdown has focus, any of the arrow keys will change the selection
- When the dropdown menu is open, clicking <kbd>Tab</kbd> or <kbd>Enter</kbd> will make a selection
###Here's a more comprehensive extension I just came up with:
The most robust way to see if an option was selected is to use the change
event, which you can handle with jQuery's .change()
handler.
The only remaining thing to do is determine if the original element was selected again.
This has been asked a lot (one, two, three) without a great answer in any situation.
The simplest thing to do would be to check to see if there was a click
or keyup
event on the option:selected
element BUT Chrome, IE, and Safari don't seem to support events on option
elements, even though they are referenced in the w3c recommendation
Inside the Select
element is a black box. If you listen to events on it, you can't even tell on which element the event occurred or whether the list was open or not.
The next best thing is to handle the blur
event. This will indicate that the user has focused on the dropdown (perhaps seen the list, perhaps not) and made a decision that they would like to stick with the original value. To continue handling changes right away we'll still subscribe to the change
event. And to ensure we don't double count, we'll set a flag if the change event was raised so we don't fire back twice:
##Updated example in jsFiddle
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
var changed = false;
$(this).focus(function () {
changed = false;
}).change(function () {
changed = true;
fn(this);
}).blur(function (e) {
if (!changed) {
fn(this);
}
});
});
};
})(jQuery);