Sunday 10 April 2011

Filter an HTML SELECT box with javascript

I searched for something like this a couple of weeks ago and NOTHING was there out there...so I did it myself.   This is a function that will filter a select box (the HTML drop-down box) using Javascript regular expressions.

To use it, add an input box as follows

<input type='text' onkeyup="searchselect('BoxID',this.value);" ></input>

(BoxID is the HTML id you gave to the SELECT box)

This means that as you type, the function will run and filter the select box.  Works really fast too (and I'm using a 2 year old dual-core).  Change the event type if you want to call it differently.

WARNING...if you have a really big list (like > 1000) and you are on IE8 or less, the performance sux.  It appears to be that the IEs are redrawing the page every time you add/remove an option.  Testing in FF 3.6/4, Chrome, Opera is sweet.

This is a list of international telecom codes by country--type in the input box to filter!

 #######################################################################
//### Andrew Cave 5/4/2011 andrew.cave.blogging \at\ gmail\\\.c\om ####
// this code is freely redistributable under GPL.
// ------------------------------------------------------------
//Description:  this function runs through the drop-down box to filter it.
//Method:load the original box into a GLOBAL array, clear the box
// then go thru the ARRAY and add each element that matches the string (using regexp)
// ####################################################################### 
var option={value:0,text:''}; //<-- this is an object to hold the info from the Select Box
var TheSelect= []; //<-- this is the GLOBAL array - defined here so it persists after the function is run

function searchselect(elem_id,filtervalue){
  //just fixing up the regex values here
    filtervalue = filtervalue.replace(/\?/g,'\\?');
    filtervalue = filtervalue.replace(/\*/g,'\\*');
    filtervalue = filtervalue.replace(/^$/,'.');
    var box = document.getElementById(elem_id); //get  the select box
//The first time we go through, TheSelect is empty so we dump
//the value and text values into
//the GLOBAL array we defined just before the function signature
    if (TheSelect.length==0){
        //copy the select list
        for(var i=0;i<box.options.length;i++){
            var option={
                    value:box.options[i].value,
                    text:box.options[i].text
                    };
            TheSelect.push(option);
        }
    }
    var sel = document.getElementById(elem_id);
    sel.length=0; //Clear the current select box
    var re = new RegExp(filtervalue,'i');
    var j=0;
    var k=TheSelect.length;
    for(var i=0;i<k;i++){
        if(filtervalue==''){//restore all the select OPTION tags that match
                var opt = document.createElement("OPTION");
                opt.text = TheSelect[i].text;
                opt.value = TheSelect[i].value;
                sel.add(opt);
        }
        else //add the matching OPTION tags
        {
            if(re.test(TheSelect[i].text)){
                var opt = new Option(TheSelect[i].text,TheSelect[i].value);
                sel.options[j]=opt;
                sel.options[j++].title=TheSelect[i].text;
            }
        }           
    }
}