NewJavaEnthusiast
NewJavaEnthusiast

Reputation: 103

How to use one request to local JSON file to populate multiple dropdowns, using jQuery?

I am trying to use Country/City dropdowns in multiple places of my project, however I am getting stuck with an unusual behaviour - when I am changing the countries. How can I make one request to get the local JSON file and populate multiple dropdowns? Here is my code:

$(document).ready(function() {
fetch('assets/test.json').then(response => {return response.json()}).then(selectData => {
  console.log(selectData)
  function updateSelectsBirth() {
      let citiesBirth = selectData[this.value].map((key, val) => {
        return $("<option />").text(key).val(key);
      });
      $("#cityBirth, #cityBirth1").empty().append(citiesBirth);
    }
    let stateBirth;
    $countryBirth = $("#countryBirth, #countryBirth1").on("change", updateSelectsBirth);        
    for (stateBirth in selectData) {
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth);
    }
    $countryBirth.change();
  })  
});

And the HTML

<select id="countryBirth"></select>
<select id="cityBirth"></select>
<br/>
<select id="countryBirth1"></select>
<select id="cityBirth1"></select>

Here's also a link to the demo project: link to the demo

Upvotes: 0

Views: 63

Answers (1)

Irene Liberali
Irene Liberali

Reputation: 401

The unexpected behaviour comes from

$("#cityBirth, #cityBirth1").empty().append(citiesBirth);

Because, when it's updating the cities, it's updating all the dropdowns instead of just one.

So you can try:

$(document).ready(function() {
fetch('assets/test.json').then(response => {return response.json()}).then(selectData => {
  // console.log(selectData)
  function updateSelectsBirth(event) {
      let citiesBirth = selectData[this.value].map((key, val) => {
        return $("<option />").text(key).val(key);
      });
      // console.log(event.data.target)
      $(event.data.target).empty().append(citiesBirth);
    }
    let stateBirth;
    $countryBirth = $("#countryBirth").on("change", {target: "#cityBirth"}, updateSelectsBirth);   
    $countryBirth1 = $("#countryBirth1").on("change", {target: "#cityBirth1"}, updateSelectsBirth);   
    // $countryBirth1 = $("#countryBirth1").on("change", updateSelectsBirth("#cityBirth1"));        
    for (stateBirth in selectData) {
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth);
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth1);
    }
    $countryBirth.change();
    $countryBirth1.change();
  })  
});

I apologize this is not a complete answer, as I'm not generalizing to multiple dropdowns, however I am not able to leave comments yet. I hope this can still be helpful.

Upvotes: 1

Related Questions