Search Server Listbox with javascript

Posted on 2007-08-06
Medium Priority
Last Modified: 2013-11-05
I have a listbox filled with items from a database and a search textbox, whatever the user type in the textbox should limit the listbox items withe text entered by the user .. my concern is the items should be limited with each letter entered in the textbox without postback ... i spent the whole day to figure it out but useless .. PLEASE HELP
Question by:eghanem
LVL 12

Expert Comment

ID: 19638153
Not exactly what your after, but if you need something up and running quick this will do the job:

It searches but doesn't remove the elements.


It could be done with an array and some funky code but someone would have to write the whole thing because i haven't seen a "download and go" control like that.
LVL 12

Expert Comment

ID: 19638173
This might also interest you, however it uses a web service call.  I've seen modifications that take out the call to the server and just use javascript.
LVL 12

Expert Comment

ID: 19638175

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

LVL 37

Accepted Solution

samtran0331 earned 1000 total points
ID: 19638203
1. Add this to the <Head> section of your form:

<script type="text/javascript">
    function filterlist(selectobj) {

      // VARIABLES

      // HTML SELECT object
      this.selectobj = selectobj;

      // Flags for regexp matching.
      // "i" = ignore case; "" = do not ignore case
      this.flags = "i";

      // Make a copy of the options array
      this.optionscopy = new Array();
      for (var i=0; i < selectobj.options.length; i++) {
        this.optionscopy[i] = new Option();
        this.optionscopy[i].text = selectobj.options[i].text;
        this.optionscopy[i].value = selectobj.options[i].value;

      // METHODS

      this.reset = function() {
      // This method resets the select list to the original state.
      // It also unselects all of the options.


      this.set = function(pattern) {
      // This method removes all of the options from the select list,
      // then adds only the options that match the pattern regexp.
      // It also unselects all of the options.
      // In case of a regexp error, returns false

        var loop=0, index=0, regexp, e;

        // Clear the select list so nothing is displayed
        this.selectobj.options.length = 0;

        // Set up the regular expression
        try {
          regexp = new RegExp(pattern, this.flags);
        } catch(e) {

        // Loop through the entire select list
        for (loop=0; loop < this.optionscopy.length; loop++) {

          // Check if we have a match
          if (regexp.test(this.optionscopy[loop].text)) {

            // We have a match, so add this option to the select list
            this.selectobj.options.length = index + 1;
            this.selectobj.options[index].text = this.optionscopy[loop].text;
            this.selectobj.options[index].value = this.optionscopy[loop].value;
            this.selectobj.options[index].selected = false;

            // Increment the index

      this.set_ignore_case = function(value) {
      // This method sets the regexp flags.
      // If value is true, sets the flags to "i".
      // If value is false, sets the flags to "".

        if (value) {
          this.flags = "i";
        } else {
          this.flags = "";



2. Add this to your form's html *after* the listbox.
(Change the "document.frmLookup.lbLookup" to the name of your form and listbox)

<script type="text/javascript">
 var myfilter = new filterlist(document.frmLookUp.lbLookup);

3. Add this to your page_load.  Change "txtLookup" to the name of your search textbox.
Me.txtLookup.Attributes.Add("onkeyup", "myfilter.set(this.value)")

*the end result (which I think you're after) is that as you type in the textbox, the items are filtered from the listbox...


Expert Comment

ID: 19638229
You need to use client-side Javascript to save all the list items to an array, and then dynamically repopulate the listbox based on the filter keys.

Something like this:

// Create an array of list items

var sel = document.forms["f1"].sel1;
var len = sel.length;

for(i=0, j=0; i<len; i++)
        if(sel.options[i].text matches filter criteria) // omitting this code - let me know if you need help
             sel_array[j++] = new Option(sel.options[i].text, sel.options[i].value);

// Populate the listbox with the context-sensitive list
for(i=0; i<filtered_array.length; i++)
     sel.options[i] = sel_array[i];

Expert Comment

ID: 19638285
I am not quite sure if I am following you, are you trying to create a auto-complete function? Is this what you are trying to do? http://www.w3schools.com/php/php_ajax_livesearch.asp ?

Expert Comment

ID: 19638298
... Ignore my post (seems that you got quite a few "helping hands" already.

Author Comment

ID: 19638840
Thanks samtran0331 for ur help it's what am looking for.. the only thing is i want to search with exact beginning letters (if the user type UK, so the suggestion will be UK, Ukraine ..  and so on ).
and yeah, one last thing :) i need the  top seggestion to be selected so the user can hit enter without complete the name ..

Assisted Solution

Netlink2 earned 1000 total points
ID: 19805063
The following code works really well for me and does everything you want.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">

Start typing a name in the input box that matches a name in the drop-down...<BR>
<INPUT TYPE="text" NAME="input1" ONKEYUP="autoComplete(this,this.form.lstSuburbs,'value',true)">

<INPUT TYPE="text" NAME="input2" ONKEYUP="autoComplete(this,this.form.options,'value',true)">

<SELECT NAME="options"
      <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

<script language="JavaScript">
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) {
            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) ;

        <asp:ListBox ID="lstSuburbs" runat="server" DataSourceID="SqlDataSource1" DataTextField="Twn" DataValueField="Twn"></asp:ListBox><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT [Twn] FROM [tlkpPostCode] WHERE ([Stt] = @Stt)">
                <asp:Parameter DefaultValue="QLD" Name="Stt" Type="String" />

Featured Post

Technology Partners: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Learn how to set-up custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question