Articles → JQUERY → Cascading drop downs in jQuery

Cascading drop downs in jQuery





  1. Software requirement
  2. Prerequisite knowledge
  3. Steps of execution
  4. Create a new project
  5. Add reference of jQuery.js
  6. Create tables in database
  7. Add data in the table
  8. Add 3 dropdowns on the page
  9. Add a method to bind dropdowns
  10. Call jQuery method to bind country drop down
  11. Call jQuery method to bind state drop down
  12. Call jQuery method to bind city drop down
  13. Output

Software requirement




  1. Visual studio 2005 (or above) is installed on your machine.
  2. Latest jQuery file i.e. jquery-latest.js (from the path http://code.jquery.com/jquery-latest.js) is downloaded on your system.
  3. SQL server 2005 (or above) is installed on your machine.

Prerequisite knowledge




  1. How to create project using visual studio?
  2. Basics about SQL server objects like tables.
  3. How to create table in SQL server?
  4. Basics about asp.net server controls like drop down, button.
  5. Basics about ADO.Net i.e. how to fetch data from SQL server?
  6. Basics about jQuery like what is ready function, how to register control’s event in jQuery etc?

Steps of execution




  1. Create a new project
  2. Add reference of jQuery.js
  3. Create tables in database
  4. Add data in the table
  5. Add 3 dropdowns on the page
  6. Add a method to bind dropdowns
  7. Call jQuery method to bind country drop down
  8. Call jQuery method to bind state drop down
  9. Call jQuery method to bind city drop down



Create a new project




Picture showing the folder structure in solution explorer

Click to Enlarge


Add reference of jQuery.js




<script src="Script/jquery-latest.js" type="text/javascript"></script>




<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>



Create tables in database




Picture showing the table schemas for country, state and city table

Click to Enlarge


Add data in the table




Picture showing the data inserted into the country, state and city table

Click to Enlarge


Add 3 dropdowns on the page




Picture showing the dropdowns when no data is bind

Click to Enlarge


Add a method to bind dropdowns




  1. GetCountry() = Method to get list of countries from Country table.
  2. GetState() = Method to get the list of states of a particular country.
  3. GetCity() = Method to get the list of cities of a particular state.


using System;
using System.Web.Services;
using System.Collections;
using System.Data.SqlClient;
using System.Data;

public partial class _Default: System.Web.UI.Page { 
  
  [WebMethod]
	public static ArrayList GetCountry() {
		DataSet resultSet = new DataSet();
		ArrayList list = new ArrayList();
		using(SqlConnection connection = new SqlConnection("connection_string")) {
			connection.Open();
			using(SqlDataAdapter adapter = new SqlDataAdapter("select country_id,country_name from Country", connection)) {
				adapter.Fill(resultSet);
			}

			if (resultSet != null) {
				if (resultSet.Tables.Count > 0) {
					list.Add(new {
						Value = "",
						Display = ""
					});
					foreach(DataRow row in resultSet.Tables[0].Rows) {
						list.Add(new {
							Value = row["country_id"],
							Display = row["country_name"]
						});
					}

				}
			}
		}
		return list;
	} 
  
  [WebMethod]
	public static ArrayList GetState(int countryId) {
		DataSet resultSet = new DataSet();
		ArrayList list = new ArrayList();
		using(SqlConnection connection = new SqlConnection("connection_string")) {
			connection.Open();
			using(SqlDataAdapter adapter = new SqlDataAdapter("select state_id,state_name from state where country_id=" + countryId, connection)) {
				adapter.Fill(resultSet);
			}

			if (resultSet != null) {
				if (resultSet.Tables.Count > 0) {
					list.Add(new {
						Value = "",
						Display = ""
					});
					foreach(DataRow row in resultSet.Tables[0].Rows) {
						list.Add(new {
							Value = row["state_id"],
							Display = row["state_name"]
						});
					}

				}
			}
		}
		return list;
	}

	[WebMethod]
	public static ArrayList GetCity(int stateId) {
		DataSet resultSet = new DataSet();
		ArrayList list = new ArrayList();
		using(SqlConnection connection = new SqlConnection("connection_string")) {
			connection.Open();
			using(SqlDataAdapter adapter = new SqlDataAdapter("select city_id,city_name from City where state_id=" + stateId, connection)) {
				adapter.Fill(resultSet);
			}

			if (resultSet != null) {
				if (resultSet.Tables.Count > 0) {
					list.Add(new {
						Value = "",
						Display = ""
					});
					foreach(DataRow row in resultSet.Tables[0].Rows) {
						list.Add(new {
							Value = row["city_id"],
							Display = row["city_name"]
						});
					}

				}
			}
		}
		return list;
	}
}





Call jQuery method to bind country drop down




$().ready(function() {
      //   Option to bind drop down from code behind
      $.ajax({
        type: "POST",
        url: "Default.aspx/GetCountry",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          $.each(msg.d, function(key, value) {
            var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
            $('#<%=ddlCountry.ClientID %>').append(option);
          });
        },
        error: function() {
          alert("Error in loading contents");
        }
      });




  1. type specifies whether you are using GET or POST method.
  2. url contains ASPX_PAGE/METHOD_NAME. For example we have a page Default.aspx and we are calling a method GetCountry to fetch list of countries so url in above code is Default.aspx/GetCountry.
  3. data means what are the input parameter we are passing in the METHOD_NAME method.
  4. contentType means encoding.
  5. dataType means the format in which the input parameter is passed in METHOD_NAME method.
  6. success means action when call is successful.
  7. error means action when call is not successful.

Call jQuery method to bind state drop down




//  Register On change event
$('#<%=ddlCountry.ClientID %>').change(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/GetState",
    data: "{countryId:" + $('#<%=ddlCountry.ClientID %>').val() + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      $('#<%=ddlState.ClientID %>').html('');
      $.each(msg.d, function(key, value) {
        var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
        $('#<%=ddlState.ClientID %>').append(option);
      });
    },
    error: function() {
      alert("Error in loading subjects");
    }
  });

});



Call jQuery method to bind city drop down




$('#<%=ddlState.ClientID %>').change(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/GetCity",
    data: "{stateId:" + $('#<%=ddlState.ClientID %>').val() + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      $('#<%=ddlCity.ClientID %>').html('');
      $.each(msg.d, function(key, value) {
        var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
        $('#<%=ddlCity.ClientID %>').append(option);
      });
    },
    error: function() {
      alert("Error in loading subjects");
    }
  });

});




$().ready(function() {
  //   Option to bind drop down from code behind
  $.ajax({
    type: "POST",
    url: "Default.aspx/GetCountry",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      $.each(msg.d, function(key, value) {
        var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
        $('#<%=ddlCountry.ClientID %>').append(option);
      });
    },
    error: function() {
      alert("Error in loading contents");
    }
  });

  //  Register On change event
  $('#<%=ddlCountry.ClientID %>').change(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetState",
      data: "{countryId:" + $('#<%=ddlCountry.ClientID %>').val() + "}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        $('#<%=ddlState.ClientID %>').html('');
        $.each(msg.d, function(key, value) {
          var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
          $('#<%=ddlState.ClientID %>').append(option);
        });
      },
      error: function() {
        alert("Error in loading subjects");
      }
    });

  });
  //   End

  //  Register On change event
  $('#<%=ddlState.ClientID %>').change(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetCity",
      data: "{stateId:" + $('#<%=ddlState.ClientID %>').val() + "}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        $('#<%=ddlCity.ClientID %>').html('');
        $.each(msg.d, function(key, value) {
          var option = '<option value="' + value.Value + '">' + value.Display + '</option>'
          $('#<%=ddlCity.ClientID %>').append(option);
        });
      },
      error: function() {
        alert("Error in loading subjects");
      }
    });

  });
});



Output


Picture showing the output of cascading dropdown in jquery

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, April 18, 2013

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250