A lot of the current solutions will break in a lot of situations. 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:
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 in the w3c recommendation
Inside the Select
element seems to be 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 then, seems 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:
###Code:
<!-- language: lang-js -->
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
$(this).focus(function () {
this.dataChanged = false;
}).change(function () {
this.dataChanged = true;
fn(this);
}).blur(function (e) {
if (!this.dataChanged) {
fn(this);
}
});
});
};
})(jQuery);
Then call like this:
<!-- language: lang-js -->
$("#dropdownid").selected(function (e) {
alert('You selected ' + $(e).val());
});
##Updated example in jsFiddle