Populate dependent dropdown from arrays only using AJAX Jquery

I'm trying to do a form with dropdown dependable options, the problem is that I can just use HTML, Javascript and Ajax, no database, so I have to fill the options directly with jquery, so far this is what I got, but is not working, any help would awesome, thank you :)

$(document).ready(function(){

    var countries =  [
           {
            "id": "1",
            "name": "Mexico"
           },
           {
            "id": "2",
            "name": "USA"
           },
           {
            "id": "3",
            "name": "Canada"
           }
           ]

   var states = {
        'mexico': [{
            display: "Ciudad de Mexico",
            value: "mx-city"
        }, {
            display: "Jalisco",
            value: "jalisco"
        }],
            'usa': [{
            display: "Texas",
            value: "texas"
        }, {
            display: "Ohio",
            value: "ohio"
        }],
            'canada': [{
            display: "Montreal",
            value: "montreal"
        }, {
            display: "Toronto",
            value: "toronto"
        }]
    };
     

     var states = {
        'mx-city': [{
            display: "Benito Juarez",
            value: "benito-juarez"
        }, {
            display: "Cuauhtemoc",
            value: "cuauhtemoc"
        }],
            'jalisco': [{
            display: "Zapopan",
            value: "zapopan"
        }, {
            display: "Guadalajara",
            value: "Guadalajara"
        }],
            'texas': [{
            display: "San Antonio",
            value: "san-antonio"
        }, {
            display: "Austin",
            value: "austin"
        }],
           'ohio': [{
            display: "Colombus",
            value: "colombus"
        }, {
            display: "Cleveland",
            value: "cleveland"
        }],
            'montreal': [{
            display: "Quebec",
            value: "Quebec"
        }, {
            display: "Vermont",
            value: "vermont"
        }],
            'toronto': [{
            display: "Ontario",
            value: "ontario"
        }, {
            display: "York",
            value: "york"
        }]
    };
   



   $("#country").on('click',function() {
      var pais = $(this).val();
      $("#country").find("option").remove();
      $(countries).each(function (i) { 
        $("#country").append('<option id="'+countries[i].id+'">'+countries[i].name+"</option>");
    });
       console.log(pais);
   });



   function list(array_list){
    $("#child_selection").html(""); 
    $(array_list).each(function (i) { 
        $("#child_selection").append('<option value="'+array_list[i].value+'">'+array_list[i].display+"</option>");
    });
   }
   


   $('#child_selection').change(function() {
     var state = $(this).val();

      if (states[state] == undefined) {
            return $("#child").text('Selecciona tu ciudad');
        }
        list(states[state]);
   });
    });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><form action="" method=""  enctype="application/json">
    <br/>Nombre: <input type="text" />
    <br/>Edad:   <input type="text" />
    <br/>Pais:
    <select name="country" id="country">
      <option value="">Selecciona tu pais</option>
    </select>
    <br />Estado:
    <select name="child_selection" id="child_selection">
      <option value="">Selecciona tu estado</option>
    </select>
    <br/>Ciudad:
    <select name="child" id="child">
      <option value="">Selecciona tu ciudad</option>
    </select>
    
    <input type="submit" value="Submit" />
  </form>

Answers 1

  • First of all you have 2 variables with the same name states and your code is not according to the format of your JSON. Below the code i have fixed. Have a look.

    $(document).ready(function() {
    
      var countries = [{
        "id": "1",
        "name": "Mexico"
      }, {
        "id": "2",
        "name": "USA"
      }, {
        "id": "3",
        "name": "Canada"
      }]
    
      var states = {
        'mexico': [{
          display: "Ciudad de Mexico",
          value: "mx-city"
        }, {
          display: "Jalisco",
          value: "jalisco"
        }],
        'usa': [{
          display: "Texas",
          value: "texas"
        }, {
          display: "Ohio",
          value: "ohio"
        }],
        'canada': [{
          display: "Montreal",
          value: "montreal"
        }, {
          display: "Toronto",
          value: "toronto"
        }]
      };
    
    
      var cities = {
        'mx-city': [{
          display: "Benito Juarez",
          value: "benito-juarez"
        }, {
          display: "Cuauhtemoc",
          value: "cuauhtemoc"
        }],
        'jalisco': [{
          display: "Zapopan",
          value: "zapopan"
        }, {
          display: "Guadalajara",
          value: "Guadalajara"
        }],
        'texas': [{
          display: "San Antonio",
          value: "san-antonio"
        }, {
          display: "Austin",
          value: "austin"
        }],
        'ohio': [{
          display: "Colombus",
          value: "colombus"
        }, {
          display: "Cleveland",
          value: "cleveland"
        }],
        'montreal': [{
          display: "Quebec",
          value: "Quebec"
        }, {
          display: "Vermont",
          value: "vermont"
        }],
        'toronto': [{
          display: "Ontario",
          value: "ontario"
        }, {
          display: "York",
          value: "york"
        }]
      };
    
    
      $(countries).each(function(i) {
        $("#country").append('<option id="' + countries[i].id + '">' + countries[i].name + "</option>");
      });
      $("#country").on('change', function() {
        list(states[$("#country").val().toLowerCase()]);
      });
    
    
      function list(array_list) {
        $("#child_selection").html("");
        $(array_list).each(function(i) {
          $("#child_selection").append('<option value="' + array_list[i].value + '">' + array_list[i].display + "</option>");
        });
      }
    
    
    
      $('#child_selection').change(function() {
        var state = $(this).val();
        if (cities[state] == undefined) {
          return $("#child").text('Selecciona tu ciudad');
        }
        array_list = cities[state.toLowerCase()];
        $("#child").html("");
        $(cities[state]).each(function(i) {
          $("#child").append('<option value="' + array_list[i].value + '">' + array_list[i].display + "</option>");
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <br/>Nombre:
      <input type="text" />
      <br/>Edad:
      <input type="text" />
      <br/>Pais:
      <select name="country" id="country">
        <option value="">Selecciona tu pais</option>
      </select>
      <br />Estado:
      <select name="child_selection" id="child_selection">
        <option value="">Selecciona tu estado</option>
      </select>
      <br/>Ciudad:
      <select name="child" id="child">
        <option value="">Selecciona tu ciudad</option>
      </select>
    
      <input type="submit" value="Submit" />
    </form>

    Hope it helps :)


Related Articles