Search code examples
jquerymysqljspjquery-ajaxq

how to show dropdown list based on selection of a particular item in other drowdown list in jquery?


I have created 2 Tables in mysql , india_states and india_cities. I have inserted values from mysql itself where india_states has 4 states , and in india_cities there are 16 city names , means one state Maharashtra in india_states table has 4 cities in india_cities table. I have successfully shown the states in a dropdown using in my html page using jquery , below is the code for the states.

$(document).ready(function(){
var states_name="";
$.ajax({
     type: 'GET', 
        url: 'http://localhost:8082/JqueryForm/html/jsp/states_name.jsp', 
        data: { get_param: 'value' }, 
        dataType: 'json',
        success: function (data) { 
        var select = $('#select_states').empty();
              $.each(data, function(i) {
                  states_name = data[i].state_name;
                  console.log("states_name:" + states_name);
                  select.append('<option value="'
                          + states_name
                          + '">'
                          + states_name
                          + '</option>')
                 });
             }
      });
});

Now what i want to do is , when i select maharashtra , the other dropdown should automatically show 4 cities related to maharashtra only , for that i have put the states_id in india_cities table. I have also created a jsp page which is used to show my cities in json view based on the following url

http://localhost:8082/JqueryForm/html/jsp/city_names.jsp?states_id=1

{
1: {
city_name: "Mumbai"
},
2: {
city_name: "Pune"
},
3: {
city_name: "Thane"
},
4: {
city_name: "Navi Mumbai"
}
}

and here is my jquery code for the above

$(document).ready(function(){
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=
    ([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}
var states_id = $.urlParam('states_id');
var cities_name="";
$.ajax({
     type: 'GET', 
        url: 'http://localhost:8082/JqueryForm/html/jsp/city_names.jsp', 
        data: { states_id: states_id }, 
        dataType: 'json',
        success: function (data) { 
        var select = $('#select_cities').empty();
              $.each(data, function(i) {
                  cities_name = data[i].city_name;
                  console.log("cities_name:" + cities_name);
                  select.append('<option value="'
                         + cities_name
                         + '">'
                         + cities_name
                         + '</option>')
            });
         }
     });
});

india_states.jsp

<%
JSONObject finalJSON = new JSONObject();
Sql_Server details = new Sql_Server();
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
List<String> list = details.getIndiaStates();
int recordCounter = 1;
JSONArray jArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
    JSONObject formDetailsJson = new JSONObject();
    formDetailsJson.put("state_name", list.get(i));
    finalJSON.put(recordCounter, formDetailsJson);
    ++recordCounter;
}
out.println(finalJSON.toString());

%>

In place of states_id when i put "1" it shows me the values of maharashtra state, but how to get the states_id dynamically ? So need some help to populate my other dropdown based on the values of first dropdown. Thank you


Solution

  • I suggest you that from your JSON, where you are collecting the value of states like :

    states_name = data[i].state_name; // get this value from your JSP like 123#Maharashtra
    

    so that in your success function you can split this value using:

    var abc=(data[i].state_name).split("#");

    and put id of the state in the value attribute of option tag.

    So, in the end you have the IDs associated with each state in your option value.

    Change in your code like this :

    $(document).ready(function(){
    var states_name="";
    $.ajax({
         type: 'GET', 
            url: 'http://localhost:8082/JqueryForm/html/jsp/states_name.jsp', 
            data: { get_param: 'value' }, 
            dataType: 'json',
            success: function (data) { 
            var select = $('#select_states').empty();
                  $.each(data, function(i) {
                      states_name = data[i].state_name;
                      var abc = states_name.split("#");
                      console.log("states_name:" + states_name);
                      select.append('<option value="'
                              + abc[0]
                              + '">'
                              + abc[1]
                              + '</option>')
    
                  });
    
            }
    });
    

    and then on the change event of your states drop down call your ajax like :

    $('#select_states').on("change", function () {
    var state_id=$('#select_states').val();
    $.ajax({
             type: 'GET', 
                url: 'http://localhost:8082/JqueryForm/html/jsp/cities_name.jsp', 
                data: { id : state_id }, 
                dataType: 'json',
                success: function (data) { 
                      //populate the cities drop down.
    
                }
        });
    
    });