Suggest As You Type - The Plan
(Page 2 of 4 )
Well, I guess before we jump into JavaScript code, I should explain quickly what we'll do, and how we'll do it. Basically, we'll have a long list of items within a <select> menu. Now, it would get unnecessarily complicated to catch our keystrokes within a menu. So what we'll do is add an input box to capture our keystrokes, and match the list items to what we type, as we type it.
OK, so let's take quick inventory of what is needed. First, the <select> menu, full of all the choices. Now this menu can be either static or dynamically populated, because this whole operation is taking place on the client's browser. We also need an input box to type in. We need the JavaScript function that handles the typed input matching. Also, I will throw in some optional in line scripting, to populate the text box with the text of a selected item. All right, we have our plan, so let's get to it.
The Code
First let's start off with our form elements, the input box and the select menu.
<form name="form1">
<input type="text" name="employeeName" onKeyUp="suggestName();" /><br />
<select name="employeeList" size="6"
onClick="javascript:form1.employeeName.value=this.options[options.selectedIndex].text;">
<%
strSQL = "SELECT employee_name FROM employees ORDER BY employee_name"
set objRs = objConn.Execute(strSQL)
while not objRs.EOF
response.write("<option value=""" & objRs(0) & """>")
response.write(objRs(0) & "</option>" & vbcrLf)
objRs.MoveNext
wend
%>
</select>
</form>
In case any of the above code is unfamiliar to you, I'll explain it for you. First of all we have our input box, and the property is set such that every time a key is released within the box, we go off the suggestName() function, to see if we can match what's now in the box.
For the select menu, the in-line scripting simply states that each time you click on an item, we're going to send the text value of the selected item to the text box. This serves one purpose here, to show that we have chosen an item. The real usefulness of doing this though, is in the case where you're not depending on the actual text of the item (employee name in this case), but really on a unique identifier, such as employee number. We don't really need to see the employee number, but we can modify the select menu to hold the UID as the value of each item, and fill in a hidden field with that id when an item is clicked (selected). This really comes into play when you're trying to ensure referential integrity in a database, maybe using the employee number as a primary key.
If that's similar to the situation you have, you can just modify the SQL statement to pull the fields you need, and append some nearly identical in-line scripting. What you will do however, is send the 'value' instead of the 'text' of the selected item, probably to a hidden field.
Next: The Suggestion Function >>
More JavaScript Articles
More By Justin Cook