-1

I want to get the key of JSON file I have, then get the value in another select input with JavaScript.

This is the JSON file I have:

"city": {
"Afghanistan": [
  "Herat",
  "Kabul",
  "Kandahar",
  "Molah",
  "Rana",
  "Shar",
  "Sharif",
  "Wazir Akbar Khan"
],
"Albania": [
  "Elbasan",
  "Petran",
  "Pogradec",
  "Shkoder",
  "Tirana",
  "Ura Vajgurore"
],

So what I want is only the country in select input, and when user selects one, all cities should be loaded into the other input.

Here is the HTML code I have:

<div class="form-group">
   <label for="Country">Country</label>
   <select class="custom-select" id="Country">
      <option selected>Choose...</option>
   </select>
 </div>
 <div class="form-group">
    <label for="ville">Ville</label>
    <select class="custom-select" id="ville">

    </select>
 </div>
juzraai
  • 5,693
  • 8
  • 33
  • 47
  • So what did you try ? – madjaoue Jul 19 '18 at 20:12
  • Possible duplicate of [get keys of json-object in JavaScript](https://stackoverflow.com/questions/8430336/get-keys-of-json-object-in-javascript) – arashka Jul 19 '18 at 20:14
  • `$.getJSON('json_file/countries.json',function (data) { jsonItem = data; console.log(data["Afghanistan"]); for (var i=0;i –  Jul 19 '18 at 20:16
  • @ArashKazemi I tried but it does not work –  Jul 19 '18 at 20:18
  • Possible duplicate of [Getting JavaScript object key list](https://stackoverflow.com/questions/3068534/getting-javascript-object-key-list) – Zackary Jones Jul 19 '18 at 20:19
  • `data["Afghanistan"]` doesn't work because it is a child of `city` if anything it would be `data["city"]["Afghanistan"]` or some other combination as you don't show the entire structure of your json. – Patrick Evans Jul 19 '18 at 20:21
  • @ZackaryJones THX `let jsonItem = []; var keys = []; $.getJSON('json_file/countries.json',function (data) { jsonItem = data; for(var k in jsonItem) keys.push(k); console.log(keys); });` –  Jul 19 '18 at 20:40

1 Answers1

0
$.getJSON("data.json", function(result){
        $.each(result.city, function(item, field){
             $('#Country').append($('<option>', { 
                text : item 
            }));
        });
});


$("#Country").bind("change", function() {
    var country = $(this).val();
    $.getJSON("data.json", function(result){
         $.each(result.city[country], function(item, field){
             $('#ville').append($('<option>', { 
                text : field 
            }));
        });
    });

})

this should work.. you could clean it up a little though

Troll173
  • 46
  • 4