How can I auto filter a HTML selectlist?

edosoft picture edosoft · Oct 9, 2008 · Viewed 7.8k times · Source

I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:

var optionsLength = dropdownlist.options.length;
  for (var n=0; n < optionsLength; n++)
  {
    var optionText = dropdownlist.options[n].text;
    if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
    {
      dropdownlist.selectedIndex = n;
      return false; 
    }
  }

The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?

Answer

MDCore picture MDCore · Oct 9, 2008

Change

if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)

to

if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)

To find dropdownlist.keypressBuffer anywhere in the optionText.