Tuesday 16 May 2017

JSON - Dynamic Dependent Select Box using Jquery and Ajax



How to make dynamic dependent dropdown list by using Jquery Ajax and JSON. Using of dependent select box will be a require functionality if there is a dependency between options of the select box fields. Dependent dropdown list box when we have select in parent select box then it will allowed to refresh child select box data without refresh of web page. In this post we have JSON file to store data for fill parent and child select box and in that file we have give relationship between Parent data with Child. We will use Ajax Jquery for fetch data from JSON file and filled parent select box. This is a very simple Ajax JQuery code hope you like this.

The dynamic dependent dropdown list box is most required for Country State and City select box. So in this post we have made relational select box of Country State City by using JQuery Ajax with JSON array data file. Here first we will filled Parent select box of with Country list fetch from JSON file by using Ajax with JQuery. And here State dependent dynamic select box data has been filled based on selection of parent Country select box. And Same way City dynamic dependent select box data has been filled based on selection of it's parent State drop down list box. That means State data has been related with selection of Country and list of City data has been related with selection of state. So here when we have select any country from select box then here it will fetch state data which are related with particular country and same way when we have select any state from select box then it will fetch city data which are related with particular state by using Ajax JQuery without refresh of web page.

In one of our previous web tutorial we have already made dynamic dependent select box by using JQuery Ajax with PHP and Mysql. But here we have do something different here we have fetch data from JSON file by JQuery Ajax and here we have not make any PHP sever side script for fetch data from Mysql database but we have use JSON File and in that we have store country state city data with state data related with country and city data has been related with state. So here we have make simple light weight dynamic dependent dropdown list box because here we have perform all operation at client side not perform any server script for fetch data from Database. So if you have developed any website and in that you have to require any dynamic dependent select box then you can choose this type JSON with Ajax JQuery instead of using PHP Mysql with Aajx JQuery.

So lastly this is our simple web tutorial on How to make dynamic dependent select by using JSON with Ajax Jquery. I hope you have enjoy this post. Please keep visit out website for Accessing Web tutorial with Source Code and online demo.







Source Code



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</h2><br /><br />
   <select name="country" id="country" class="form-control input-lg">
    <option value="">Select country</option>
   </select>
   <br />
   <select name="state" id="state" class="form-control input-lg">
    <option value="">Select state</option>
   </select>
   <br />
   <select name="city" id="city" class="form-control input-lg">
    <option value="">Select city</option>
   </select>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 load_json_data('country');

 function load_json_data(id, parent_id)
 {
  var html_code = '';
  $.getJSON('country_state_city.json', function(data){

   html_code += '<option value="">Select '+id+'</option>';
   $.each(data, function(key, value){
    if(id == 'country')
    {
     if(value.parent_id == '0')
     {
      html_code += '<option value="'+value.id+'">'+value.name+'</option>';
     }
    }
    else
    {
     if(value.parent_id == parent_id)
     {
      html_code += '<option value="'+value.id+'">'+value.name+'</option>';
     }
    }
   });
   $('#'+id).html(html_code);
  });

 }

 $(document).on('change', '#country', function(){
  var country_id = $(this).val();
  if(country_id != '')
  {
   load_json_data('state', country_id);
  }
  else
  {
   $('#state').html('<option value="">Select state</option>');
   $('#city').html('<option value="">Select city</option>');
  }
 });
 $(document).on('change', '#state', function(){
  var state_id = $(this).val();
  if(state_id != '')
  {
   load_json_data('city', state_id);
  }
  else
  {
   $('#city').html('<option value="">Select city</option>');
  }
 });
});
</script>


country_state_city.json



[
 {
  "id":"1",
  "name":"USA",
  "parent_id":"0"
 }, 
 {
  "id":"2",
  "name":"Canada",
  "parent_id":"0"
 }, 
 {
  "id":"3",
  "name":"Australia",
  "parent_id":"0"
 }, 
 {
  "id":"4",
  "name":"New York",
  "parent_id":"1"
 }, 
 {
  "id":"5",
  "name":"Alabama",
  "parent_id":"1"
 }, 
 {
  "id":"6",
  "name":"California",
  "parent_id":"1"
 }, 
 {
  "id":"7",
  "name":"Ontario",
  "parent_id":"2"
 }, 
 {
  "id":"8",
  "name":"British Columbia",
  "parent_id":"2"
 }, 
 {
  "id":"9",
  "name":"New South Wales",
  "parent_id":"3"
 }, 
 {
  "id":"10",
  "name":"Queensland",
  "parent_id":"3"
 }, 
 {
  "id":"11",
  "name":"New York city",
  "parent_id":"4"
 }, 
 {
  "id":"12",
  "name":"Buffalo",
  "parent_id":"4"
 }, 
 {
  "id":"13",
  "name":"Albany",
  "parent_id":"4"
 }, 
 {
  "id":"14",
  "name":"Birmingham",
  "parent_id":"5"
 }, 
 {
  "id":"15",
  "name":"Montgomery",
  "parent_id":"5"
 }, 
 {
  "id":"16",
  "name":"Huntsville",
  "parent_id":"5"
 }, 
 {
  "id":"17",
  "name":"Los Angeles",
  "parent_id":"6"
 }, 
 {
  "id":"18",
  "name":"San Francisco",
  "parent_id":"6"
 }, 
 {
  "id":"19",
  "name":"San Diego",
  "parent_id":"6"
 }, 
 {
  "id":"20",
  "name":"Toronto",
  "parent_id":"7"
 }, 
 {
  "id":"21",
  "name":"Ottawa",
  "parent_id":"7"
 }, 
 {
  "id":"22",
  "name":"Vancouver",
  "parent_id":"8"
 }, 
 {
  "id":"23",
  "name":"Victoria",
  "parent_id":"8"
 }, 
 {
  "id":"24",
  "name":"Sydney",
  "parent_id":"9"
 }, 
 {
  "id":"25",
  "name":"Newcastle",
  "parent_id":"9"
 }, 
 {
  "id":"26",
  "name":"City of Brisbane",
  "parent_id":"10"
 }, 
 {
  "id":"27",
  "name":"Gold Coast",
  "parent_id":"10"
 }
]


48 comments:

  1. very nice tutorials sir please provide Individual column searching (multiple dropdown select filter datatable)

    ReplyDelete
  2. Since most marketers cannot or do not want to control the distribution function com- pletely, structuring channel relationships becomes a crucial task.
    http://www.atozexams.com/

    ReplyDelete
  3. the city doesn't change when changing the country

    ReplyDelete
  4. Hi This is working but using this with SUBMIT button not returning any value

    ReplyDelete
  5. Hi, thx for usefull codes. I just wonder how can we add function like; if any of last dropdown options selected, website will redirect to url which related to specific option.
    New york city goes to www.example.com
    Buffalo goes to www.example1.com
    Albany goes to www.example2.com

    ReplyDelete

  6. excellent article, it served me a lot

    ReplyDelete
  7. can you do a version using arrays?

    ReplyDelete
  8. Above you have a three level drop down, what if I have a five level?

    ReplyDelete
  9. Above is a 3 level drop down. I need a 4 and a 5, and I'm struggling to update the JavaScript. Any help would be appreciated

    ReplyDelete
  10. When I post my form into database ids are passed instead of names, what's the solution?

    ReplyDelete
    Replies
    1. Hi can you explain how you got value as name instead of ID.please help

      Delete
    2. How to get value as name instead of value as ID into database

      Delete
  11. Instead of a .json file can you load a .txt or .csv or .js file? Is so what would be the code? My server doesn't allow me to use .json that's why...

    ReplyDelete
  12. Its not working . please check the source code

    ReplyDelete
    Replies
    1. Your correct but open this file in the Microsoft Edge (or updated browser)because some of the older browser [doesnot support] JSON,JQUERY,JSON

      Delete
  13. Hi there,

    It works almost for me, i wanne post (email) the choses, but wen i e-mail them it gives the id an not the name of the chosen city.

    How can i change that ?

    ReplyDelete
    Replies
    1. not working on mine. what did you do?

      Delete
    2. So Write name="email" , It take email field , For Password , name="password"

      Delete
  14. it's not working can somebody please do help me

    ReplyDelete
  15. If we put the script part in the first page inside the head tag the program actually works.

    ReplyDelete
  16. it works fine if you put the script part inside head tag in the first page

    ReplyDelete
  17. Any way to make the parent id work for two ID's? For example if there is a town called "Springfield" in New York and California and you don't want to repeat the JSON block. Something like {"id":"17","name":"Springfield", "parent_id":"6/7"}.

    ReplyDelete
  18. When I put it in a for loop the value in the Country only display in the first instance.

    ReplyDelete
  19. when I execute the code I get
    country_state_city.json
    Request Method: GET
    Status Code: 404

    ReplyDelete
  20. when I execute the code I get
    country_state_city.json
    Request Method: GET
    Status Code: 404

    ReplyDelete
  21. Hello friends,
    You must run on virtual machines wampserver, html does not work.

    ReplyDelete
  22. How can we add more things (Link on Submit button), I mean, when we do select the last one and hit submit button a new link/page will open.

    ReplyDelete
  23. Its not working...
    please check the source code...
    And Put Right Code Here So Sume Learner Are Not fatch Trouble If Any One Have Solution For This Code So Please Put Here...

    ReplyDelete
  24. Hello.
    Great content but does this not work for firefox or google chrome? Only seem to work on edge.

    ReplyDelete
  25. Hello.
    Great content but does this not work for firefox or google chrome? Only seem to work on edge.

    ReplyDelete
  26. Can't get it work, even after I move the script inside the head tag

    ReplyDelete
  27. I put the script inside the body tag however the options at the menu drop-down won't work, please someone could help?

    ReplyDelete
  28. give name="email" , It Take Email Field Then....

    ReplyDelete
  29. could nor load the json file

    ReplyDelete
  30. when i select country, state and city then show me those image.

    imagine i select USA and i want to see USA's flag in the bottom.

    can you help me please @Weblesson

    ReplyDelete
  31. It is not working. It does not produce any message where wrong!

    ReplyDelete
  32. withou firefox: Create dynamic web project in using eclipse or any ID. create jsp file name index.jsp under webcontent folder. then script part put under head part.
    then create json file under webcontent.
    Finally run on tomcat or any server. it would be fine.

    ReplyDelete
  33. Cannot get this to work, no matter where I put the script. The demo works, but on my own machine, no dice.

    ReplyDelete
  34. When I save the values in text file I am getting value as ID but I need value as name.please help

    ReplyDelete
  35. Hello tks for the script....but if i wont to write in the db only value name and not value id....how to? tks

    ReplyDelete
  36. hi tks for the script....but,How to get value as name instead of value as ID into database..please

    ReplyDelete
  37. How to get value as name instead of value as ID into database.. please help

    ReplyDelete