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
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.
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/