Skip to content

Using numeric values to select item from a dropdown box with JavaScript

I have a multitude of dropdown boxes within my web page. One of these dropdown boxes is used for a single selected value out of a list of options.

<SELECT id="Box0" name="">

<OPTION value="1920">my weird description</OPTION>

<OPTION value="1225">other weird description</OPTION>

<OPTION value="3112">some name dynamically fetched</OPTION>
</SELECT>

How can I add an event to this section, so when it is in focus, I could use numeric keys like 1,2.. to select an option instead of using the mouse or arrow keys for selecting an option? For clarification: if I press 1 on my keyboard, the selected value would become the first value from that list, with 2 the selected value becomes second value from that list.

I choose not to use a library/framework such as JQuery/Mootools.

Answer

I think this can solve your problem

<html>
<head>
<script type="text/javascript">
    function selectvalue(e){
        e = e || event;

        var key = e.which || e.keyCode;

        if(!e.shiftKey && key >= 48 && key <= 57){
            var option = this.options[key - 48];
            if(option){
                option.selected = "selected";
            }
        }
    }
</script>
</head>
<body>

    <SELECT id="Box0" name="" onkeypress="selectvalue.apply(this, arguments)">
        <OPTION value="1920">my weird description</OPTION>
        <OPTION value="1225">other weird description</OPTION>
        <OPTION value="3112">some name dynamically fetched</OPTION>
    </SELECT>

</body>
</html>

The javascript looks little messy because it has to handle IE and all other browsers.

IE does not pass an event object to the handler function instead we have to use the global event object.

Same way the keycode also is stored in keyCode instead of which in IE.