I have this dropdown
, I want to alert/log something when the value in it is changed. What happens is when I click the dropdown
with mouse, and selected any other value, the change event is fired. But when the focus is in the dropdown
, and I press up
and down
arrow, it changes the value in dropdown, but the event is not fired, and the alert is now showing up.
Here's the code
<select id="drpDay" name="drpDay" style="background-color: white;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7" selected="selected">7</option>
</select>
</br>
<select id="drpMonth" name="drpMonth" style="background-color: white;">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
<option value="May">May</option>
<option value="Jun">Jun</option>
<option value="Jul">Jul</option>
<option value="Aug">Aug</option>
<option value="Sep">Sep</option>
<option value="Oct">Oct</option>
<option value="Nov" selected="selected">Nov</option>
<option value="Dec">Dec</option>
</select>
</br>
<label id="lbl" text="" width="auto">adsf</label>
The js is
$('#drpDay, #drpMonth').change(function(event) {
alert(event.which);
$('#lbl').text('change ' + event.which + ' and ' + $(event.target).attr('id'));
});
Here's the fiddle http://jsfiddle.net/2NBPx/4/
What I want is when the value in select box changes, event by pressing up
and/or down
arrow, I want that event to be fired. Why is not firing, and how do I make it fire on change from keyboard?
Bind it to keyup and change like so: http://jsfiddle.net/2NBPx/6/
$('#drpDate, #drpMonth').on('change keyup',function(event) {
if($(this).data('last') !== $(this).val()){
$(this).data('last', $(this).val());
$('#lbl').text('For change ' + event.which + ' and you ' + $(event.target).attr('id'));
}
});
UPDATE: is only fired when an actual change happens.
The following will ensure that the change event fires whenever the selection changes, via the keyboard or the mouse.
var prevValue = null;
$('#drpDay').change(function() {
console.log('changed');
prevValue = this.value;
});
$('#drpDay').keyup(function() {
if(prevValue != this.value) {
$(this).trigger('change');
}
});
Check this demo: http://jsfiddle.net/ZCxe8/
What browser are you using ?
In my Chrome and IE9, the fiddle that you provided works fine with the keyboard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With