Populate a select dropdown list using jQuery and Ajax

28

Posted by Joe | Posted in Ajax, JavaScript, jQuery | Posted on 23-02-2010

In this post I’ll explain how to populate a select dropdownlist using jQuery and Ajax.  I am using an ASP.NET web application and page methods to perform the Ajax calls.  Using page methods means that you do not need a seperate web service, which is good if the functionality is specifically for the page.  The page methods must be declared public static and use the WebMethod attribute. 

 Download source

First of all here is the contents of my form with two select lists, one for gender and one for names.  Each list is given a unique ID to be able to reference them in jQuery.  The intention here is to display a list of genders in the first list, which when selected populates the second select with a list of names for that gender. 

<table>
    <tr>
        <th>
            Gender
        </th>
        <td>
            <select id="ddlGender">
            </select>
        </td>
    </tr>
    <tr>
        <th>
            Name
        </th>
        <td>
            <select id="ddlName">
            </select>
        </td>
    </tr>
</table>

Here is the page method that gets my list of genders: 

[WebMethod]
public static ArrayList GetGenders()
{
    return new ArrayList()
    {
        new { Value = 1, Display = "Male" },
        new { Value = 2, Display = "Female" }
    };
}

For the purpose of the example I am just returning an ArrayList of an anonymous type containing a value and display text which will be converted to JSON in jQuery and used to populate the select list.  You could easily replace this code to get some data from a database if required. 

Here is the method used to get the list of names based on the selected gender.  I will be passing the Value property from the anonymous gender type through to this method to filter the list of names: 

[WebMethod]
public static ArrayList GetNames(int genderID)
{
    if (genderID.Equals(1))
    {
        return new ArrayList()
        {
            new { Value = 1, Display = "Joe" },
            new { Value = 2, Display = "Tom" },
            new { Value = 3, Display = "Sylvain" }
        };
    }
    else if (genderID.Equals(2))
    {
        return new ArrayList()
        {
            new { Value = 4, Display = "Emily" },
            new { Value = 5, Display = "Lauri" },
        };
    }
    else
    {
        throw new ApplicationException("Invalid Gender ID");
    }
}

Again I am returning an ArrayList of an anonymous type containing a list of names depending on the genderID passed into the method. 

Now for the fun part, hooking it all up with jQuery.  First I need to populate the gender list when the page loads: 

   

$().ready(function() {
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetGenders",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $("#ddlGender").get(0).options.length = 0;
            $("#ddlGender").get(0).options[0] = new Option("Select gender", "-1");   

            $.each(msg.d, function(index, item) {
                $("#ddlGender").get(0).options[$("#ddlGender").get(0).options.length] = new Option(item.Display, item.Value);
            });
        },
        error: function() {
            alert("Failed to load genders");
        }
    });
});   

 

Here I am using jQuery’s Ajax method to make a call to the GetGenders page method.  In the successful callback from the call I then do the following: 

Clear the select list’s current items: 

$("#ddlGender").get(0).options.length = 0;

Add an item at the top of the list prompting to select a gender with a value of -1, I’ll check this value later before making a call to GetNames: 

$("#ddlGender").get(0).options[0] = new Option("Select gender", "-1");

Loop through the results of the Ajax call and add the items to the list: 

$.each(msg.d, function(index, item) {
    $("#ddlGender").get(0).options[$("#ddlGender").get(0).options.length] = new Option(item.Display, item.Value);
});

Now the gender dropdown list is populated when the page loads. Next I need the names list to be populated when choosing a gender.  To do this I have created a JavaScript function called GetNames which accepts the genderID as a parameter: 

 

function GetNames(genderID) {
    if (genderID > 0) {
        $("#ddlName").get(0).options.length = 0;
        $("#ddlName").get(0).options[0] = new Option("Loading names", "-1"); 

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetNames",
            data: "{genderID:" + genderID + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#ddlName").get(0).options.length = 0;
                $("#ddlName").get(0).options[0] = new Option("Select name", "-1"); 

                $.each(msg.d, function(index, item) {
                    $("#ddlName").get(0).options[$("#ddlName").get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function() {
                $("#ddlName").get(0).options.length = 0;
                alert("Failed to load names");
            }
        });
    }
    else {
        $("#ddlName").get(0).options.length = 0;
    }
} 

  

First I check if the genderID is greater than zero, if not (the ‘Select gender’ item has been chosen) then clear the names list.  If it is I clear the list and add an option with the text Loading names to the select list as I did with gender.  This will be displayed while the Ajax call is being made to let the user know something is happening.  Next I use the same approach as getting the list of gender to get the list of names but I pass a JSON string through as the data property containing the selected gender ID.  The successful callback works in the same way as populating the list of genders. 

Finally I need this method to be called when a gender is selected so I’ve added the following to my successful Ajax callback underneath the loop that populates the genders: 

$("#ddlGender").bind("change", function() {
    GetNames($(this).val());
});

This binds the onChange event to call the GetNames function passing through the selected gender ID.

 Download source

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit

Comments (28)

We can replace
$.each(msg.d, function(index, item) {
$(“#ddlName”).get(0).options[$("#ddlName").get(0).options.length] = new Option(item.Display, item.Value);
});

index instead of “$(“#ddlName”).get(0).options.length] ” in the above code

Hi Venkat

Good tip, thanks.

Joe

Hi Venkat,

The update -
index instead of “$(“#ddlName”).get(0).options.length] ” in the above code
-
returns a different result than the original: “Select name” is replaced.

index+1 is fine

Hi Joe,

Thanks for this, it’s just what I’m after. The only problem is I am having trouble compiling.

I’m working in Visual Web Developer 2008 Exp and have .net 3.5 installed. I can compile your sample code but as soon as I try to compile an exact copy of your web method in my code it comes up with around 45 errors all asking for ‘;’s or type expected etc… in and around the web method. Have you any ideas what may be causing it?

Cheers
Cap

Hi Cap

Not really sure without seeing it. Have you got all the necessary using statements?

Cheers
Joe

Make sure that you are working on an AJAX Enabled WebSite. Otherwise, you may not be able to make server calls.

The Webservice you create should be using the Name Space System.Web.Script.Services; [ScriptService] attribute has to be added.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyService : System.Web.Services.WebService
{

Thanks for the code & tutorial, needed to use ajax on a page, which had a drop down list, of companies and people. Was going to use an UpdatePanel, though it got messy when trying to use the UpdateProgress control, hence used a variant of your code.

Taking it a step further, I cleaned it up, by using something like:

$(‘#ddlName’).empty().append(‘Loading Names’);

And used:

$(‘#ddlName’).append(” + item.Display + ‘</option');

In the for loop.

Forgive the lack of left brackets, they seem to have been removed, however you can guess what they would look like….

hi friend,
i want to clear Second drop down once i m selecting first drop down ..

i tried following code for that also

$(‘#drpGenderHobby).empty().append(‘-All-’).find(‘option:first’).attr(“selected”, “selected”);

but in my case it is not working fine..
i also tried your give way

$(“#ddlName”).get(0).options.length = 0;
$(“#ddlName”).get(0).options[0] = new Option(“Select name”, “-1″);

but in this case i am not getting desire output

looking for positive reply

thanks in advance.

hi,
Thanks for the code & tutorial

Try this.

$(‘#>option’).remove();
$(“#”).append($(”).val(‘-1′).html(“–Select One–”));

Hi, Iam new to jquery could u plz tell how to bind dropdownlist with C# Generic list. Acctually m using SQL server which return me a generic list but i dont know how to handle it.
Thanks

Khizar

My example uses an ArrayList, you can easily swap it out for a generic list.

SQL Server won’t be giving you a generic list, it’ll be whatever ORM/data access method you’re using. With my example you need a web service method that returns the data you get from the database.

Cheers
Joe

Hi!
Anyone knows what is the meaning of the “.d” in the msg.d that we give as a parameter to the populating function? Thanks

Hi Asaf

Where are you seeing msg.d?

Joe

Thanks for the example.
I have a requirement where I need to show the combo-box on selection of value from another combo-box. That I am able to achieve through your example above.
Now I need to know two things :-

1. Why option tag not visible under select tag when I do View Source on the IE even if the values have been filled in combo-box successfully.
2. I need to hide the combo-box when page loads and then need to display when the comb-box is populated through Ajax call.

Gaurav

It won’t be visible when you view source as it’s loaded into the DOM via ajax.

For showing the combo after population you could initially add a display:none style to it, then in the ajax callback use jQuery.Show to display it.

Cheers
Joe

Hi, thanks for the code, very useful, but I have an issue, in your code you have:

$.each(msg.d, function(index, item)

But I had to coded like this

$.each(eval(‘(‘ + msg.d + ‘)’), function(index, item)

Because otherwise item would return and array with size of the total of characters in the msg.d string; therefore giving me item.Value and item.Display as undefined

Do you know why this happens? I’m making a web application on VS 2010 (framework 4), in my web method (the one that is called via Ajax) I serialize a List whit the JavaScriptSerializer object. I don’t know if this has something to do with it

Hi Asaf, hope this answer your question about the “.d” parameter

http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/

Thank you… It works like a charm..

Why don’t you offer a demo to view functionality? This is good information but it could be better supplemented with the demo.

Jovanky

Just download the source and try it for yourself.

Regards
Joe

thanks ..good works

Thank you very much, this helped me a lot!

Hello, how will i implement this using the converted datatable —> arraylist?

how will i populate the drop down list… the item.Sample doesn’t work.

Thanks!

Hi

Just set the Value and Display properties of the anonymous object from values in your datatable using dt["ColumnName"]

Cheers
Joe

Write a comment