Populate a select dropdown list using jQuery and Ajax

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

Posted on by Joe in Ajax, JavaScript, jQuery

39 Responses to Populate a select dropdown list using jQuery and Ajax

  1. Venkat

    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

  2. Joe

    Hi Venkat

    Good tip, thanks.

    Joe

  3. Izzat

    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.

  4. Izzat

    index+1 is fine

  5. Captastic

    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

  6. Joe

    Hi Cap

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

    Cheers
    Joe

  7. AK Sabin

    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
    {

  8. Jonathan Stichbury

    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.

  9. Jonathan Stichbury

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

  10. Jayesh

    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.

  11. omid

    hi,
    Thanks for the code & tutorial

  12. Ajay

    Try this.

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

  13. Khizar

    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

  14. Joe

    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

  15. Pingback: Populate a select dropdown list using jQuery and Ajax « Techno World

  16. asaf

    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

  17. Joe

    Hi Asaf

    Where are you seeing msg.d?

    Joe

  18. Gaurav Jain

    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.

  19. Joe

    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

  20. thx0125

    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

  21. thx0125

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

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

  22. Ravi

    Thank you… It works like a charm..

  23. Jovanky De Los Santos

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

  24. Joe

    Jovanky

    Just download the source and try it for yourself.

    Regards
    Joe

  25. tana

    thanks ..good works

  26. Mar Anthony Go

    Thank you very much, this helped me a lot!

  27. RUSTY CODER

    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!

  28. Joe

    Hi

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

    Cheers
    Joe

  29. Omm

    Hi Joe,
    Thanks for your simple and fine example.

    when i tried the with “Onclick()” of Select Element, nothing binds.

    *** “my web method returns array”.

    $.fn.pplDdl = function () {
    var ddl = this.attr(“id”).toString();
    $(‘#’ + ddl).bind(“change”, function () {
    getFlds($(this).val());
    });

    };

    function getFlds(ddl) {
    $(‘#’ + ddl).get(0).options.length = 0;
    alert(“line1″);
    $(‘#’ + ddl).get(0).options[0] = new Option(“Loading names”, “-1″);
    alert(“Loading names”);
    $.ajax({
    type: “POST”,
    url: “default.aspx/binddl”,
    data: “{” + ddl + “}”,
    contentType: “application/json; charset=utf-8″,
    dataType: “json”,
    success: function (msg) {
    $(‘#’ + ddl).get(0).options.length = 0;
    $(‘#’ + ddl).get(0).options[0] = new Option(“Select name”, “-1″);

    $.each(msg.d, function (index, item) {
    $(‘#’ + ddl).get(0).options[$('#' + ddl).get(0).options.length] = new Option(item.Display, item.Value);
    });
    },
    error: function () {
    $(‘#’ + ddl).get(0).options.length = 0;
    $(‘#’ + ddl).get(0).options[0] = new Option(“Failed to Load”, “-1″);
    alert(“Failed to load”);
    }
    });

    }

  30. Dan

    Hi Joe

    Great work, thanks. I’ve got it working, but when i post back the dropdownlist items have been cleared out. Is there anyway to persist?

    Thanks

  31. Joe

    Hi Dan

    Would be a few ways. What are you using? Web Forms or plain HTML?

    Cheers
    Joe

  32. Joe

    Omm

    Where are you using OnClick? Also, is there a reason why you’d want to hook into the OnClick event? That would fire as soon as you click on the select input.

    Joe

  33. Manisha

    I want to know what datatypes can be returned from webservice method for Ajax calls other than arraylist and strings..

  34. Joe

    Have a look here: http://msdn.microsoft.com/en-us/library/ms531031%28v=vs.85%29.aspx

    Pretty much anything that’s serializable should work. You can return your own classes.

  35. Hitesh Agja

    Nice post ! Keep up good work.

    I have also created similar kind of work in my blog to populate gridview(asp.net) using jquery ajax.

    here is the link if anybody want to see http://hiteshagja.com/populate-data-in-gridview-using-jquery-ajax/

  36. gayathri

    hi im new to jquery.
    can u pls help me out to populate a second select box on changing the first by calling a json data without using array.

  37. gayathri

    hi
    can u pls help me out to populate a second select box on changing the first by calling a json data without using array?

  38. Pingback: [RESOLVED]Bind values from database to HTML Select Tag | ASP Questions & Answers

  39. Soft Sunrise

    Very NICE AND GOOD ajax jquery database and php learning

Add a Comment