kalyan said:
Hi All
I'm a newbie to javascript.
I had a textbox in my webpage.when i try to type something then a list
of matching values should be dispalyed underneath the textbox.
I can provide the list of values thru an array
my requirement seems something like the functionality in the following
site
http://www.google.com/webhp?complete=1&hl=en
Thanks & Regards
Kalyan
Markup (adapt to SGML if XHTML doesn't fit your needs):
<input type="text" id="MyTextBox" />
<!-- absolute position removes it from document flow -->
<select id="MySelect" style="position:absolute">
</select>
Script:
//minimum number of characters to activate autocomplete
var MIN_TEXT_LENGTH = 3;
var MyPossibleValues = ['Lorem', 'LoremTest', 'Ipsum', 'IpsumTest'];
document.getElementById("MyTextBox").onkeypress = function()
{
if(this.value.length < MIN_TEXT_LENGTH)
return;
var selectBox = document.getElementById("MySelect");
//clear select box
while(selectBox.childNodes.length > 0)
selectBox.removeChild(selectBox.childNodes[0]);
//check beginning of each possible value against text box
//case insensitive
for(var i = 0; i < MyPossibleValues.length; i++)
{
if(MyPossibleValues
.substring(
0, this.value.length).toLowerCase() ==
this.value.toLowerCase())
{
//this option matched
//add it to the select box
var option = document.createElement("option");
option.appendChild(
document.createTextNode(
MyPossibleValues));
selectBox.appendChild(option);
}
}
//make select box expand to fit all the options
//without scrolling
selectBox.size = selectBox.childNodes.length;
}
If you want the select box to change the text box you'll have to add
additional logic for that.
This code is just an example. I didn't even test it and it's probably
riddled with errors and typos.
Jeremy