Reputation: 454
<select size="5">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
<option>e</option>
</select>
Naturally, when I press a, b, c, d, or e, this jumps to the option with that as the first letter. I need to disable this, preferably not through Javascript (not required).
Is there really no way to turn off this keypress jump to letter option?
Upvotes: 0
Views: 930
Reputation: 716
Copied from: https://stackoverflow.com/a/1227324
<script type="text/javascript">
function IgnoreAlpha(e)
{
if (!e)
{
e = window.event ;
}
if (e.keyCode >= 65 && e.keyCode <= 90) // A to Z
{
e.returnValue=false;
e.cancel = true;
}
}
</script>
<body>
<p>
<select id="MySelect" name="MySelect" onkeydown="IgnoreAlpha(event);"">
<option selected="selected" value="" />
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</p>
</body>
Upvotes: -1
Reputation: 12472
You cannot do it without JavaScript.
With JavaScript you will need to add an event handler for keypress
event, to prevent default behavior and to stop propagation.
With jQuery:
$("select").on("keypress", function (event) {
event.preventDefault();
event.stopPropagation();
});
Take care that $("select")
will select all your select inputs and you'll end up adding this keypress
for all of them.
Without jQuery:
<select id="mySelect" size="5">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
<option>e</option>
</select>
var select = document.getElementById('mySelect');
select.addEventListener ("keypress", function (event) {
event.preventDefault();
event.stopPropagation();
});
Working fiddle: https://jsfiddle.net/ep3xfyc8/9/
Later edit: There exists a solution to achieve this without JavaScript. See Lee Kowalkowski's response below.
Upvotes: 2
Reputation: 11751
You can do it without JavaScript.
Prefix every option with a Zero-Width Non Joiner character.
<label for="select">Select:</label>
<select size="5" id="select">
<option>‌a</option>
<option>‌b</option>
<option>‌c</option>
<option>‌d</option>
<option>‌e</option>
</select>
If this is going to be submitted in a HTTP request, the ‌
character should be ignored by the browser. Every option should have its own value
attribute for form submission purposes, anyway, and you would not need to put the ‌
character into the option values.
Upvotes: 3
Reputation: 7735
This is an adaption of what @razvan-dimitru proposes but keeping JS to a minimum. In a way, you only need markup for this solution:
<select onkeyup='event.preventDefault(); event.stopPropagation();'>
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
<option>e</option>
</select>
Upvotes: 0