Dynamic Lookup
June 22, 2004 · 1 Comment
On a new system I'm developing, I had the need for the user to type into a standard text box and for the cursor to move to the specific entry in a corresponding select box.
Now, when you hit the first key, it does exactly what it should. For example, if you hit 'c' on your keyboard, the select box will highlight the first entry beginning with 'c'.
The problem arises when you then type 'h', in that you're actually looking for entries in the select box that start with 'ch'. However, what actually happens is that the select box moves to the first entry beginning with 'h'. Definately not what I was after.
The solution is a little bit of JavaScript.
The HTML that makes up my form is like so...
<input type="text" name="Start" onkeyup="JumpTo(this.form)" class="standard" />
<br /><br />
<select name="centre_id" multiple="no" size="10">
<cfoutput query="select_centres">
<option value="#centre_id#">#centre_name#</option>
</cfoutput>
</select>
As you can see here, on every onKeyUp action for the text box, a function called JumpTo is called.
The code for the JumpTo function is as follows:
<br /><br />
<select name="centre_id" multiple="no" size="10">
<cfoutput query="select_centres">
<option value="#centre_id#">#centre_name#</option>
</cfoutput>
</select>
function JumpTo(thisForm) {
var SelectItem = 0;
var stringSub = thisForm.Start.value.toUpperCase();
for (i=0; i� thisForm.centre_id.length; i++) {
var stringMain = thisForm.centre_id[i].text.toUpperCase();
if (stringMain.indexOf(stringSub) == 0) {
SelectItem = i;
break;
}
}
if (SelectItem != 0) {
thisForm.centre_id.selectedIndex = SelectItem;
}
}
What the function does, is to simply match what we've typed into the text box against the entries in the select box, and if we have a match, then we set the selectedIndex property of the select box to that item. var SelectItem = 0;
var stringSub = thisForm.Start.value.toUpperCase();
for (i=0; i� thisForm.centre_id.length; i++) {
var stringMain = thisForm.centre_id[i].text.toUpperCase();
if (stringMain.indexOf(stringSub) == 0) {
SelectItem = i;
break;
}
}
if (SelectItem != 0) {
thisForm.centre_id.selectedIndex = SelectItem;
}
}
Tags: JavaScript

1 response so far ↓
1 ed hardy mens Jeans // Sep 17, 2009 at 9:22 AM
Leave a Comment