Search Server Listbox with javascript

Posted on 2007-08-06
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

    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

    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

    LVL 37

    Accepted Solution

    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...

    LVL 7

    Expert Comment

    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];
    LVL 3

    Expert Comment

    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? ?
    LVL 3

    Expert Comment

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

    Author Comment

    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 ..
    LVL 1

    Assisted Solution

    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" "">

    <html xmlns="" >
    <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

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Join & Write a Comment

    Suggested Solutions

    Thoughout my experience working on eCommerce web applications I have seen applications succumbing to increased user demand and throughput. With increased loads the response times started to spike, which leads to user frustration and lost sales. I ha…
    Introduction A frequently used term in Object-Oriented design is "SOLID" which is a mnemonic acronym that covers five principles of OO design.  These principles do not stand alone; there is interplay among them.  And they are not laws, merely princ…
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
    Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…

    730 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

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now