Solved

Using xmlhttp to populate a dropdown list with text and value

Posted on 2006-07-21
1
209 Views
Last Modified: 2008-03-10
I am very new to javascript and expecially xmlhttp.  

I have been able to successfully implement a solution which retrieves data from an SQL DB as a user enter text into a text box.  Basically, what is happening is the user is attempting to enter a company name, and as the company name is entered into the textbox, on each onkeyup event the DB is queried and returns the top 5 companies whose name matches the entered string.  

This is working pretty well, except that the req.responseText is being applied to the innerHTML of a DIV.  I am interested in populating a dropdown list with companyname as the text and company_id as the value. Ideally, this would be a dropdown list that you can enter text into at run time instead of entering the search criteria into a separate text box.  As the user types, their entry stays at the top of the list and returned data populates the list.

Is this possible?

The javascript runs on an asp.net web form and uses another aspx helper file which builds the sql and runs the query onload.  Here is how I am doing this:

<script type="text/javascript">
var req;

function Initialize()
{
    try
    {
        req=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            req=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            req=null;
        }
    }
    if(!req&&typeof XMLHttpRequest!="undefined")
    {
    req= new
    XMLHttpRequest();
}

} function SendQuery(key)
    {
//Here is the url of the helper page which builds and runs the SQL query
    Initialize(); varurl="http://localhost/bdsearch/newpersonhelper.aspx?s=3&k="+key;
    if(req!=null)
    {
        req.onreadystatechange = Process;
        req.open("GET", varurl, true);
        req.send(null);
    }
}

function Process()
{
    if (req.readyState == 4)
        {
        // only if "OK"
            if (req.status == 200)
            {
                if(req.responseText=="")
                    HideDiv("autocomplete");
                else
                {
                    ShowDiv("autocomplete");
                  //This is where the returned req.responseText populates the div
                  //I would like to populate the dropdown here instead.
                    document.getElementById("autocomplete").innerHTML =req.responseText;
                }
            }
            else
            {
                document.getElementById("autocomplete").innerHTML= "There was a problem retrieving data:<br>"+req.statusText;
            }
        }
}

function ShowDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="show";
   else document.getElementById(divid).style.visibility="visible";
}

function HideDiv(divid)
{
   if (document.layers) document.layers[divid].visibility="hide";
   else document.getElementById(divid).style.visibility="hidden";
}

function BodyLoad()
{
    HideDiv("autocomplete");
    document.form1.keyword.focus();

}
</script>
<html>
<form>
INPUT id="keyword" onkeyup="SendQuery(this.value)" style="WIDTH: 500px" name="keyword" autocomplete="off">
</form>
</html>

and the codebehind of the helper aspx file (varurl="http://localhost/bdsearch/newpersonhelper.aspx?s=3&k="+key;):

 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim keyword As String = Request("k")
        Dim QueryScope As String = Request("s")
        Dim sql As String
        If keyword <> Nothing And keyword.Trim() <> "" Then
            Select Case QueryScope
                Case "1" ' Normal Query
                    sql = "select top 5 company, company_id from company where company like '" + keyword.Trim().Replace("'", "''") + "%' order by company"
                Case "2" 'anything before or after keyword
                    sql = "select top 5 company, company_id from company where company like '%" + keyword.Trim().Replace("'", "''") + "%' order by company"
                Case "3" ' anything before or after keyword and THE %Keyword%
                    sql = "select top 5 company, company_id from company where company like '" + keyword.Trim().Replace("'", "''") + "%' or company like 'the " + keyword.Trim().Replace("'", "''") + "%' order by company"
            End Select

            Dim conn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
            conn.Open()
            Dim dt As DataTable = New DataTable()
            Dim command As SqlCommand = New SqlCommand(sql, conn)
            Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
            adapter.Fill(dt)
            conn.Close()

            Dim row As DataRow
            For Each row In dt.Rows
                'Response.Write("<strong>" + row("Company").ToString() + "</strong> <br />")
                Response.Write(row("Company").ToString() + "<br />")

            Next
        End If

    End Sub


Any ideas?

Thanks,
Aaron
0
Comment
Question by:abenage
1 Comment
 
LVL 19

Accepted Solution

by:
nschafer earned 500 total points
ID: 17156597
Hi abenage,

See my tutorial on this topic at http://www.applicationgroup.com/tutorials/MultiDropDownXMLHTTP.asp

Hope this helps,
Neal.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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…

705 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

18 Experts available now in Live!

Get 1:1 Help Now