Click here to Skip to main content
15,861,125 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have two dropdown lists how to bind that using jquery from back end

What I have tried:

$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
url: "ddlBind.aspx/ddlDataBind",
data: {},
dataType: "json",
success: function (data) {
var SharedAOC = JSON.parse(data.d);
var finalData = SharedAOC.Table;
debugger;
$.each(finalData, function (key, value) {
$("#ddlCity").append($("<option></option>").val(value.City).html(value.City));
$("#ddlState").append($("<option></option>").val(value.State).html(value.State));

});
debugger;
$.each(finalData, function (key, value) {
$("#ddlState").append($("<option></option>").val(value.State).html(value.State));

});

},
Posted
Updated 11-Nov-16 2:36am
Comments
F-ES Sitecore 11-Nov-16 7:14am    
What's wrong with the code you have at the moment?

(hint: saying "it doesn't work" adds no value and does not give people the information they need to help you)

refer inline comments
C#
var stateCity = []; // state City Mapping Array
      $.each(finalData, function (key, value) {  // load all the state city to an array
          stateCity.push([value.State, value.City]);
      });

      var distinctState = [];
      stateCity.forEach(function (item) { // find the distinct state
          if(distinctState.indexOf(item.State)== -1)
              distinctState.push(item.State)
      });
      distinctState.forEach(function (item) { // populate the distinct state to state ddl
          $("#ddlState").append($("<option></option>").val(item).html(item));
      });

      populateCity($("#ddlState").val()); // load the city for selected state


      function populateCity(state)   // function to load the cities based on the selection of state
      {

          $("#ddlCity").empty();
          stateCity.forEach(function (item) {
              if(item.State == state)
                  $("#ddlCity").append($("<option></option>").val(item.City).html(item.City));
          });
      }


add onchange event to the ddlstate dropdown

JavaScript
onchange="populateCity(this.value)"
 
Share this answer
 
First, you have to know how to construct dropdownlist in HTML, i.e. the select tag, then replicate it in jQuery, see example:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    //Assuming the cityCode and cityName come from the back end
    var cityCode = "sg";
    var cityName = "Singapore";
    $("#ddlCity").append("<option value='"+ cityCode +"'>"+ cityName+"</option>");
});
</script>
</head>
<body>
<select id="ddlCity"></select>
</body>
</html>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900