Suggest As You Type - The Suggestion Function
(Page 3 of 4 )
Ok, now that we have that clear in our minds, let's see how to do the actual suggestion function.
<script language="javascript">
function suggestName( level )
{
if ( isNaN( level ) ) { level = 1
}
This is just some simple error checking. This prevents run-time errors in case the function somehow gets called in an incorrect fashion (with a parameter other than an integer). Also, you'll notice that when we call it from the text box, we're not supplying any parameter at all, so 'level' gets initialized to 1. As we'll see in a second, the 'level' just helps us call the function recursively until we've matched all of the letters possible.
var f = document.form1;
var listbox = f.employeeList;
var textbox = f.employeeName;
These are more or less the only three variables that we need to modify to just pop this script into any page we have and use it. The names are fairly self-explanatory, so I'll move on.
var soFar = textbox.value.toString();
var soFarLeft = soFar.substring(0,level).toLowerCase();
var matched = false;
var suggestion = '';
What happened here, is that we're taking what's been typed into the text box, and taking a chunk of it to the length of 'level'. This means that if you paste a six letter word into the text box, the function will first start by only matching the first letter, then the second, and so on. This is important, because it means that you'll always see the closest match, even if there is no exact match for the letters you've typed. Now let's get into the search mechanism.
for ( var m = 0; m < listbox.length; m++ ) {
suggestion = listbox.options[m].text.toString();
suggestion = suggestion.substring(0,level).toLowerCase();
if ( soFarLeft == suggestion ) {
listbox.options[m].selected = true;
matched = true;
break;
}
}
So what this chunk of code does, is iterate through the list, grabbing the portion of each item, left-trimming it to the size of 'level'. If it's matched, we set that item to be selected, trip the boolean 'matched' flag, and break out of the loop. If no match is found after going through the entire list, the function exits, and we're left with the last selected item, the one closest to what we've typed. If a match is found however, we run through the function again, this time incrementing the level first, to see if we can perhaps find an ever closer match. We can do that like this:
if ( matched && level < soFar.length ) { level++; suggestName(level) }
}
</script>
And that's it, that's the wonderful 'suggest as you type' function that I use over and over in my forms.
Next: The End >>
More JavaScript Articles
More By Justin Cook