Reputation: 366
Here is the structure of my HTML :
<select class="chosen-select" data-placeholder="Choose an color:">
<option value="1">red</option>
<option value="2">blue</option>
<option value="3">green</option>
<option value="4">black</option>
</select>
And here is the javascript portion, in here it shows how easy it is to bind a click event :
$(document).on('click', '.active-result', function () {
var color = $(this).text()
})
// do something with color
I have tried binding to key up/down and keypress with success. But :
Here is my use case :
I need to bind the event to the ENTER key, I have tried binding the event to e.which == 13
and prevent defaults but with no success. Also I have to mention that this piece of code is applied to a bootstrap Modal.
Upvotes: 0
Views: 1710
Reputation: 366
I was able to solve the problem with binding the event to the chosen( ) :
$(".chosen-select").chosen().keydown ( function (e) {
if (e.which == 13 )
{
var color = $(this).val()
}
});
Upvotes: 0
Reputation: 8868
This would get you the color and change the value of the dropdown on keypress - Enter.
$(document).on('keydown', '.chosen-select', function (e) {
if (e.which == 13 )
{
var selectedTarget = $(this).find("option:selected");
alert($(selectedTarget).text());
$(this).val($(selectedTarget).val());
}
});
http://jsfiddle.net/ghjhjz03/4/
Upvotes: 1
Reputation: 3315
Try attaching the keydown event of jQuery:
$(document).on('keydown', '.chosen-select', function (event) {
if ( event.which == 13 ) {
event.preventDefault();
var color = $(this).text();
// do something with color
}
})
Upvotes: 1