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.
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.
Here is the page method that gets my list of genders:
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:
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:
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:
Loop through the results of the Ajax call and add the items to the list:
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:
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:
This binds the onChange event to call the GetNames function passing through the selected gender ID.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < table > < tr > < th > Gender </ th > < td > < select id = "ddlGender" > </ select > </ td > </ tr > < tr > < th > Name </ th > < td > < select id = "ddlName" > </ select > </ td > </ tr > </ table > |
1 2 3 4 5 6 7 8 9 | [WebMethod] public static ArrayList GetGenders() { return new ArrayList() { new { Value = 1, Display = "Male" }, new { Value = 2, Display = "Female" } }; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | [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" ); } } |
Now for the fun part, hooking it all up with jQuery. First I need to populate the gender list when the page loads:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | $().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:
1 | $( "#ddlGender" ).get(0).options.length = 0; |
1 | $( "#ddlGender" ).get(0).options[0] = new Option( "Select gender" , "-1" ); |
1 2 3 | $.each(msg.d, function (index, item) { $( "#ddlGender" ).get(0).options[$( "#ddlGender" ).get(0).options.length] = new Option(item.Display, item.Value); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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:
1 2 3 | $( "#ddlGender" ).bind( "change" , function () { GetNames($( this ).val()); }); |
No comments:
Post a Comment