This article will explain how to populate a select dropdownlist using jQuery and Ajax.  This article has ASP.NET web application and page methods to perform the Ajax calls.  Using page methods means that 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. 

Loading a drop down list using jquery ajax with example

Loading a drop down list using jquery ajax with example

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. 

Gender
Name

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: 

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 jQuerys 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 lists 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, Ill 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 Ive 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

Click here to downlaod the source