Reputation: 688
I have a Select List and I want when changes option select list and Enter Key pressed the run jquery function. This is my code:
$("#productlist").keydown(function(){
//for example
alert('Enter Pressed');
});
<select id="productlist">
<option id="1" value="1">1<option>
<option id="2" value="2">2<option>
<option id="3" value="3">3<option>
<option id="4" value="4">4<option>
</select>
Upvotes: 3
Views: 4075
Reputation: 136
You can do a check for a keypress event.
The key is 13 for Enter getting clicked.
So the event does not run every time the Enter key is clicked, you can add an extra check that makes sure the suitable input is in focus.
i.e. the function will only run if the input is selected first.
// If a key is pressed
$(document).on('keypress', function (event) {
// If the key is Enter
if (event.which == 13) {
// If the suitable input is selected / focus / active
if ($('#name-of-element').is(':focus')) {
console.log('enter clicked');
}
}
});
Upvotes: 0
Reputation: 36
Check out the keypress
approach. whenever the key takes any action, it will callback. It will be work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<select id="productlist">
<option id="1" value="1">1</option>
<option></option>
<option id="2" value="2">2</option>
<option></option>
<option id="3" value="3">3</option>
<option></option>
<option id="4" value="4">4</option>
<option></option>
</select>
<script>
$("#productlist").keypress(function(){
//for example
console.log('Enter Pressed');
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 1480
Try this
$("#productlist").keydown(function(e){
if (e.keyCode == 13) {
alert('Enter Pressed');
}
});
Upvotes: 0
Reputation: 9974
If I understood you question correct, you want to do some stuff when user selects the item from dropdown list.
$('select').change(function(){
var text = $(this).val();
alert(text);
});
Update: Above code will work for mobile devices also.
Upvotes: 1
Reputation: 177691
That is not expected behaviour. Also it does not work on mobile devices
on("change"
is better if there is no button to click.
You will have to add a "please select" option for that to work.
If you want to have the enter key submit, add a submit button. That will have the added value of allowing mobile and screen reader users to also use your interface
Upvotes: 1