Articles → JQUERY → Cascading drop downs in jQuery

Cascading drop downs in jQuery
































Software requirement











Prerequisite knowledge

















Steps of execution

























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












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");
        }
      });



















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