• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 437
  • Last Modified:

Updating a dropdown box based on textbox

I have a simple dropdown box filled with usernames pulled from a database. Like 1000 names. I want the user to be able to filter the names in the list by entering data into a textbox. Say they enter "clau" the dropdown only shows names containing the string "clau". I'm thinking there is simple code for onchange in the textbox to update the sql stament for the combobox, but I'm not sure how to write it. Again I want the full list but everytime the user enters a letter I want it combobox to be filtered.

This is what I have now.

<%
Set Conn = Server.CreateObject("ADODB.Connection")
conn.open "DSN=asset"
%>
<FORM NAME = "form" ACTION = "user.asp" METHOD = "POST">
<p>Who is the request for:</p>
<p>Enter Name or Choose from the list&nbsp; </p>
<p><select size="1" name="title">
<option selected>--Select a User--</option>  
<%
     sql = "SELECT Name FROM Users WHERE Name is not null ORDER BY Name asc"
     oRS.Open sql, Conn,1,2
     Do While Not oRS.EOF
        Response.Write"<Option Value= '" & oRS("Name") &"'>"
        Response.Write oRS("Name") & "</option>"
        oRS.MoveNext
     loop
%>                  
</select>&nbsp;&nbsp;&nbsp;
<input type="text" name="txtPhone1" value="-- Enter Name --" size="14">
</p>
<p><input type="submit" value="Submit" name="B2"></p>
</form>
0
t1clausen
Asked:
t1clausen
  • 4
  • 2
1 Solution
 
rohanbairat3Commented:
You can fill in the values in a javascript array and then on keydown or some other event ... u can alter the dropdownlist ...by reading the element in an array...

If you are thinking of executing a SQL statement on every key ...i dont think its a good idea ..

-rons
0
 
t1clausenAuthor Commented:
That probable would make more sense huh? Any suggestions on where to find some samle code for something like that? I think I can probably figure it out but I'm not sure to to refresh the dropdown. If I alter the array will it do it automaticly? I do I just sound like an idiot now ;-)
0
 
fritz_the_blankCommented:
Here are a few examples. Of course, you will still populate the list programatically, but I am giving full working samples:

Sample 1:

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT LANGUAGE=javascript>
<!--
var to_find = "";              // Variable that acts as keyboard buffer
var timeoutID = "";           // Process id for timer (used when stopping
                            // the timeout)
timeoutInterval = 400;        // Milliseconds. Shorten to cause keyboard
                            // buffer to be cleared faster
var timeoutCtr = 0;           // Initialization of timer count down
var timeoutCtrLimit = 3 ;     // Number of times to allow timer to count
                            // down

function idle(){

 timeoutCtr += 1
 if(timeoutCtr > timeoutCtrLimit){
    to_find="";
    timeoutCtr = 0;
    window.clearInterval(timeoutID);
 }
}

function findMatch(selectBox, txtFind, objEvent) {
if (txtFind == '' || objEvent.keyCode == 8) {
     return;
}

// Key press buffer

// Stop Timer
window.clearInterval(timeoutID)

var c = String.fromCharCode(objEvent.keyCode);
c = c.toLowerCase();
to_find += c;

 // Reset timer
 timeoutID = window.setInterval("idle()", timeoutInterval);  

allWords = selectBox.options;
var posLow = 0;
var posHigh = selectBox.options.length;
var foundIt = false;
var st2 = new String(to_find);
s2 = st2.toLowerCase();
while (posLow <= posHigh) {
     posMid = Math.floor((posLow + posHigh) / 2);
     s = selectBox.options[posMid].text;
     st = new String(s);
     s = st.toLowerCase();

     if (s.indexOf(s2) == 0) {
          foundIt = true;
          selectBox.selectedIndex = posMid;

             // Highlight the remaining text
             
             var typed_string = new String(s2);
             var total_string = new String(s);
             var t = total_string.length - (total_string.length - typed_string.length);
             end_string = total_string.substr(t, total_string.length);
             txtFind.value = s;
             if (end_string != "") {
                  var range = txtFind.createTextRange();
                  range.findText(end_string)
                 range.select();
             }
             
          break;
     } else {
          if (s2 < s) {
               posHigh = posMid - 1;
          } else {
               posLow = posMid + 1;
          }
     }
}

if (!foundIt) {
     selectBox.selectedIndex = 0;
}


}
//-->
</SCRIPT>


</HEAD>
<BODY>
<form>
    <select name="theselect">
         <option></option>
         <option>alah</option>
         <option>blah</option>
         <option>blue</option>
         <option>clah</option>
         <option>dlah</option>
         <option>elah</option>
         <option>flah</option>
         <option>glah</option>
         <option>hlah</option>
         <option>ilah</option>
         <option>jlah</option>
         <option>klah</option>
         <option>llah</option>
         <option>mlah</option>
         <option>nlah</option>
         <option>olah</option>
         <option>plah</option>
         <option>qlah</option>
    </select>
    <input type="text" onKeyUp="findMatch(this.form.theselect, this, event);" />

</form>


</BODY>
</HTML>


FtB
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
fritz_the_blankCommented:
Sample 2:

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT LANGUAGE=javascript>
<!--
function findOption(strText,strOption){
      objForm = document.forms[0];
      objSelect = objForm.elements[strOption];
      intStringLength = strText.length;
      for(i=0;i<objSelect.length;i++){
            strDisplayText = objSelect.options[i].text.substring(0,intStringLength);
            if(strDisplayText.toUpperCase() == strText.toUpperCase()){
                  objSelect.selectedIndex=i;
                  break;
            }
      }
}
//-->
</SCRIPT>

</HEAD>
<BODY>
<FORM action="" method=POST id=form1 name=form1>
<INPUT type="text" id=text1 name=text1 onKeyUp="findOption(this.value,'select1')">
<SELECT id=select1 name=select1>
      <OPTION></OPTION>
      <OPTION>Adam</OPTION>
      <OPTION>Bob</OPTION>
      <OPTION>Cappy</OPTION>
      <OPTION>Charlie</OPTION>
      <OPTION>Connie</OPTION>
      <OPTION>Edward</OPTION>
</SELECT>
</FORM>

</BODY>
</HTML>


FtB
0
 
fritz_the_blankCommented:
Sample 3:

<HTML>
<HEAD>
<TITLE>JavaScript Toolbox - Auto-Complete</TITLE>
<SCRIPT LANGUAGE="JavaScript">
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// -------------------------------------------------------------------
// autoComplete (text_input, select_input, ["text"|"value"], [true|false])
//   Use this function when you have a SELECT box of values and a text
//   input box with a fill-in value. Often, onChange of the SELECT box
//   will fill in the selected value into the text input (working like
//   a Windows combo box). Using this function, typing into the text
//   box will auto-select the best match in the SELECT box and do
//   auto-complete in supported browsers.
//   Arguments:
//      field = text input field object
//      select = select list object containing valid values
//      property = either "text" or "value". This chooses which of the
//                 SELECT properties gets filled into the text box -
//                 the 'value' or 'text' of the selected option
//      forcematch = true or false. Set to 'true' to not allow any text
//                 in the text box that does not match an option. Only
//                 supported in IE (possible future Netscape).
// -------------------------------------------------------------------
function autoComplete (field, select, property, forcematch) {
      var found = false;
      for (var i = 0; i < select.options.length; i++) {
      if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
            found=true; break;
            }
      }
      if (found) { select.selectedIndex = i; }
      else { select.selectedIndex = -1; }
      if (field.createTextRange) {
            if (forcematch && !found) {
                  field.value=field.value.substring(0,field.value.length-1);
                  return;
                  }
            var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
            if (cursorKeys.indexOf(event.keyCode+";") == -1) {
                  var r1 = field.createTextRange();
                  var oldValue = r1.text;
                  var newValue = found ? select.options[i][property] : oldValue;
                  if (newValue != field.value) {
                        field.value = newValue;
                        var rNew = field.createTextRange();
                        rNew.moveStart('character', oldValue.length) ;
                        rNew.select();
                        }
                  }
            }
      }
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#FFFFFF LINK="#00615F" VLINK="#00615F" ALINK="#00615F">

<U><B>Description:</B></U>
<BR>

This script is used when you have two form elements working together on a page - an input box and a select box.
<P>
A common practice to simulate a Windows "Combo Box" is to have a text box where a user can type a value, plus a select box which holds valid options. If the user selects an option from the select box, it gets filled into the text box.
<P>
This script allows you add better presentation to this concept by completing the user's entry as they type into the text box. As it matches options available in the select list, the option gets selected and (in IE) the text-entry box is auto-completed and highlighted. This works in a way similar to many Windows programs.

<BR><BR>
<U><B>Example:</B></U>
<BR>

<FORM>

<B>Auto-Complete</B><BR>
Start typing a name in the input box that matches a name in the drop-down...<BR>
<INPUT TYPE="text" NAME="input1" VALUE="" ONKEYUP="autoComplete(this,this.form.options,'value',true)">
<SELECT NAME="options"
onChange="this.form.input1.value=this.options[this.selectedIndex].value">
      <OPTION VALUE="adam">adam
      <OPTION VALUE="george">george
      <OPTION VALUE="matt">matt
      <OPTION VALUE="bill">bill
      <OPTION VALUE="greg">greg
      <OPTION VALUE="bob">bob
      <OPTION VALUE="david">david
      <OPTION VALUE="ryan">ryan
</SELECT>

</FORM>

</BODY>
</HTML>


FtB
0
 
t1clausenAuthor Commented:
That second one did the trick!

<html><head>
<title>Requestor Information</title>
<SCRIPT LANGUAGE=javascript>
<!--
function findOption(strText,strOption){
     objForm = document.forms[0];
     objSelect = objForm.elements[strOption];
     intStringLength = strText.length;
     for(i=0;i<objSelect.length;i++){
          strDisplayText = objSelect.options[i].text.substring(0,intStringLength);
          if(strDisplayText.toUpperCase() == strText.toUpperCase()){
               objSelect.selectedIndex=i;
               break;
          }
     }
}
//-->
</SCRIPT>
</head>
<body>
<FORM NAME = "form" ACTION = "user.asp" METHOD = "POST">
<p>Who is the request for:</p>
<%
Set Conn = Server.CreateObject("ADODB.Connection")
conn.open "DSN=asset"
Set oRS=Server.CreateObject("ADODB.RecordSet")
%>
<INPUT type="text" id=text1 name=text1 onKeyUp="findOption(this.value,'title')">
<p><select size="1" name="title">
<option selected>--Select a User--</option>  
<%
sql = "SELECT Name FROM Users WHERE Name is not null ORDER BY Name asc"
oRS.Open sql, Conn,1,2
Do While Not oRS.EOF
  Response.Write"<Option Value= '" & oRS("Name") &"'>"
  Response.Write oRS("Name") & "</option>"
  oRS.MoveNext
loop
%>
</p>                  
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
0
 
fritz_the_blankCommented:
Oh good. That is the one that I wrote! The others I found on the web.

FtB
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now