Solved

Using xmlhttp to populate a dropdown list with text and value

Posted on 2006-07-21
1
240 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
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…
Suggested Courses

615 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