Search code examples
selecttype-ahead

No frills (non-jQuery) type-ahead for dropdowns?


If I have a bare dropdown box, what is the easiest no frills way to add type ahead?

There is nothing complicated or dynamic about the box itself, it just has a lot of options (here, US States).

Essentially I'm wondering if this simple case can be done in a few lines of code if I'm willing to give up on all the other features like AJAX.


Solution

  • This should work:

    <head>
        <script type="text/javascript">
        function typeDropdown(typedStr,ddObj) {
            var index = ddObj.getElementsByTagName("option");
            for(var i = 0; i < index.length; i++) {
                 if(index[i].firstChild.nodeValue.toLowerCase().substring(0,typedStr.length) == typedStr.toLowerCase()) {
                      index[i].selected = true;
                      break;
                 }
            }
        }
        </script>
    </head>
    <body>
        <form>
        <input type="text" name="search" onkeyup="typeDropdown(this.value,this.parentNode.dd);" />
            <select name="dd">
                <option>Your Options</option>
                <option>Here</option>
        </select>
        </form>
    </body>
    

    It's not as pretty, but I think this is the simplest you can get.