Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to create an autocomplete select box

form elements

How to create an autocomplete select box

by  nmath  Posted    (Edited  )
I wanted to create a text box that allowed a user to start typing a word and if it was in the select box it would auto-complete. This is the code that I used to solve the problem. There is a text box that as the user inputs characters it searches the select box for matches, also if the user selects a value from the select box the text box is auto filled.

[color red]
Code:
<script language="javascript">
function fillin()
{
var mytext = Mainform.mytext.value;
sellength = Mainform.wholetext.length;
var i;

for(i = 0; i<sellength; i++)
{
   if (Mainform.wholetext.options[i].text.toLowerCase().indexOf(mytext.toLowerCase(),0) == 0)
     {Mainform.wholetext.options[i].selected = true;
     break;}
}

}

function filltext()
{
var selectedItem = Mainform.wholetext.selectedIndex;
var selectedText = Mainform.wholetext.options[selectedItem].text;

Mainform.mytext.value = selectedText;
} 
</script>

Here is the HTML section:
<form name = "Mainform">
<input type = "text" name = "mytext" onkeyup = "fillin()">

<select name = "wholetext" onclick = "filltext()">
 <option>Red</option>
 <option>Red Flowers</option>
 <option>Green</option>
 <option>Grass</option>
</select>
</form>
[/color]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top