0

Подскажите,как сделать список стран и городов используя JSON. Со странами все ок, получилось. Не могу понять, как сделать по событию onclick, выпадающий список с городами нужной страны.

<!DOCTYPE html>
<html lang="en", lang="ru">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Homework12</title>
</head>
<body>
    <div id = countryCity>
        <select id="country" type="text">Country</select>
        <select id="city" type="text">City</select> 
    </div>

<script>
var requestUrl = 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json';
var xhr = new XMLHttpRequest();

xhr.open('GET', requestUrl, true);
xhr.responseType = 'json';
xhr.send() 

xhr.onload = function() {
  var countryList = xhr.response;
  countryFunction(countryList);
}

function countryFunction(jsonObj) {
  for (var key in jsonObj){
    var countryName = document.createElement('option');
    countryName.innerHTML = key;
    country.append(countryName);

country.onchange = function(){
      
      }
    }
  }

</script>
</body>
</html>


2 ответа 2

1

Слушаем select#country, после выбора страны получаем её, делаем запрос на сервер за городами и отрисовываем их

var requestUrl = 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json';
var xhr = new XMLHttpRequest();

xhr.open('GET', requestUrl, true);
xhr.responseType = 'json';
xhr.send()

xhr.onload = function() {
  var countryList = xhr.response;
  countryFunction(countryList);
}

function countryFunction(jsonObj) {
  for (var key in jsonObj){
    var countryName = document.createElement('option');
    countryName.innerHTML = key;
    country.append(countryName);
  }
}

document.querySelector('#country').addEventListener('change', function() {
  const chosenCountry = this.value
  // xhr делаем запрос городов по выбранной стране и помещаем список в select#city
})
<div id = countryCity>
    <select id="country" type="text">
      <option value="">Выберете страну</option>
    </select>
    <select id="city" type="text">
      <option value="">Выберете город</option>
    </select>
   </div>

0

    <form action="">
        <select id="countrySelect" name=""></select>
        <select id="citySelect" name=""></select>
    </form>

    <script>


        fetch('https://raw.githubusercontent.com/russ666/all-countries-and-cities-json/master/countries.json')
            .then(res => res.json())
            .then(json => {

                let jsObj = json
                for (let key in jsObj) {

                    let countryOption = document.createElement('option');
                    let countrySelect = document.getElementById('countrySelect');

                    countryOption.innerHTML = key;
                    countrySelect.appendChild(countryOption);


                }
                document.querySelector('#countrySelect').addEventListener('change', function () { // Замыкание
                    let cities = jsObj[this.value]

                    citySelect.length = 0;

                    for (const iterator of cities) {

                        let cityOption = document.createElement('option');
                        let citySelect = document.getElementById('citySelect');

                        cityOption.innerHTML = iterator;
                        citySelect.appendChild(cityOption);
                    }
                })
            })

    </script>
</body>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.