How (using javascript or jQuery) can I detect when a value has been selected from a select box, even if it\'s the same option as was previously selected (i.e. no change even
I think focus() function will help you..try this: http://api.jquery.com/focus/
I have no idea if it would work just from the top of my head if you could attach an event handler to the select box option element and on click store its value.
works with mouse, doesn't work with keyboard http://jsfiddle.net/w4DEJ/4/
The only solution I found workable is to cause change
event by setting the value of select
to some other on mousedown
. In the markup I created one extra option (i.e. the first child) and made it hidden (hides perfectly in Chrome/FF/Safari, IE as usual). So it looks fine.
<select>
<option style="display: none"></option>
<option>First</option>
<option>Second</option>
<option>Third</option>
</select>
Then using jQuery we bind change
and mousedown
events in a way that when mousedown
triggers, select
resets its value to the value of the hidden option.
$("select").on({
change: function() {
console.log($(this).val());
},
mousedown: function() {
$(this).val($(":first", this).val());
}
});
DEMO: http://jsfiddle.net/LzNrS/
UPDATE: In order to preserve the selected value when user has clicked on select
but decided not the choose anything, we can modify the code a bit adding blur
event and updating mousedown
.
var special = ""; // special hidden option value
var value = ""; // temporary variable
$("select").on({
change: function() {
console.log($(this).val());
},
mousedown: function() {
if (this.value == special) {
$(this).val(value);
return;
}
value = this.value;
$(this).val(special);
},
blur: function() {
if (this.value == special)
$(this).val(value);
}
});
DEMO: http://jsfiddle.net/LzNrS/1/