Wrox Home  
Search P2P Archive for: Go

  Return to Index  

html_code_clinic thread: Incremental searching in Select TAG


Message #1 by gbrown@c... on Tue, 2 Oct 2001 12:33:21
Hi
I do not think there is a way to do this directly by keystrokes.
When I have done this in the past I have used the following:
<html>
<head>
<script>
// first sort all the values into alphabetical order
function sortSelect()
{
  for(i = 0; i < mySelect.options.length; i++)
  {
    for(j = i; j < mySelect.options.length; j++)
    {
      tempValue = mySelect.options[i].value;  // temp values to swap
      tempText = mySelect.options[i].text;
      if(mySelect.options[i].text.toLowerCase() > mySelect.options
[j].text.toLowerCase())
      {
        // swap values
        mySelect.options[i].text = mySelect.options[j].text;
        mySelect.options[i].value = mySelect.options[j].value;
        mySelect.options[j].text = tempText;
        mySelect.options[j].value = tempValue;
      }
    }
  }
}

// search for word
function searchSelect()
{
  sText = txtOption.value.toLowerCase();
  for(i = 0; i < mySelect.options.length; i++)
  {
    if(sText < mySelect.options[i].text.toLowerCase())
    {
      // textbox value is less that current option, so select it and stop
      mySelect.selectedIndex = i;
      break;
    }
  }
}
</script>
</head>

<body onload="sortSelect()">
<input type="text" id="txtOption" onkeyup="searchSelect()">

<select id="mySelect" size="4">
<option value="dave">David
<option value="andy">Andrew
<option value="chris">Chris
<option value="bob">Bob
</body>
</html>

When the page loads, the options are sorted into alphabetical order, and 
when the user types in the textbox, the code moves through until the 
closest value is found.  Once you have the right index, you can do 
whatever you want.

Good luck
Philip

  Return to Index