如何在运行时从另一个列表中填充选择列表?

时间:2018-12-27 13:16:59

标签: javascript jquery html json

我尝试根据国家/地区列表填充城市列表 使用 jscript 创建列表和 json 作为数据文件 和 jquery 用于在用户更改所选国家/地区列表索引时收听更改方法。

经过测试,它可以正常工作,但是没有出现城市列表,但是当我在Chrome中打开调试模式时,它会出现在HTML源代码中。

需要帮助来解释此问题并加以解决。

var _countries =
[
  { "id": "1", "Country": "USA"},
  { "id": "2", "Country": "CANADA"},
  { "id": "3", "Country": "GERMANY"}
];

var _citeis =
[
  { "countryID": "1", "id": "1", "City": "New York" },
  { "countryID": "1", "id": "2", "City": "California" },
  { "countryID": "2", "id": "3", "City": "Toronto" },
  { "countryID": "3", "id": "4", "City": "Berlin" },
  { "countryID": "3", "id": "5", "City": "Hamburg" },
  { "countryID": "3", "id": "6", "City": "Munich" },
];
var countries = _countries;
var countriesDiv = document.getElementById("_countriesList");
var countriesselectList = document.createElement("select");
countriesselectList.id = "countriesList";
countriesDiv.appendChild(countriesselectList);
//Create and append Countries to the options
for (var i = 0; i < countries.length; i++) {
    var countriesoption = document.createElement("option");
    countriesoption.value = countries[i].id;
    countriesoption.text = countries[i].Country;
    countriesselectList.appendChild(countriesoption);
}


$('#countriesList').change(function () {
    //populate Cities list
    var cities = _cities;
    var citiesDiv = document.getElementById("_citiesList");
    var citiesselectList = document.createElement("select");
    citiesselectList.id = "citieslist";
    citiesDiv.appendChild(citiesselectList);
    //Create and append Cities to the options
    for (var i = 0; i < cities.length; i++) {
        {
            if (cities[i].countryID == countriesselectList.value) {
                var citiesoption = document.createElement("option");
                citiesoption.value = cities[i].id
                citiesoption.text = cities[i].City;
                citiesselectList.appendChild(citiesoption);
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="_countriesList" class="col s12">
     <!-- Create Countries List Here -->
</div>
<div id="_citiesList" class="col s12">
     <!-- Create Cities List Here -->
</div>

更新-实施代码后的结果

<div id="cities_list" class="col s12">
    <!-- Cities List -->
    <div class="select-wrapper">
        <span class="caret">▼</span><input type="text" class="select-dropdown" readonly="true" data-activates="select-options-bf789281-0252-e649-5f47-1ae7002cf997" value="Dakar"><ul id="select-options-bf789281-0252-e649-5f47-1ae7002cf997" class="dropdown-content select-dropdown ">
            <li class=""><span>Dakar</span></li>
            <li class=""><span>Touba</span></li>
            <li class=""><span>Thiès</span></li>
            <li class=""><span>Rufisque</span></li>
            <li class=""><span>Ziguinchor</span></li>
            <li class=""><span>Diourbel</span></li>
            <li class=""><span>Louga</span></li>
        </ul>
        <select id="citieslist" class="initialized">
            <option value="1">Jeddah</option>
            <option value="2">Khobar</option>
            <option value="3">Madina</option>
            <option value="4">Riyadh</option>
            <option value="5">Yanbu</option>
            <option value="6">Jubail</option>
        </select>
    </div>
</div>

----为什么我有2个列表,而当我选择一个新国家时,页面上显示的第一个列表是不可更改的。

4 个答案:

答案 0 :(得分:1)

您可以使用.filter()仅提取具有正确国家/地区代码的城市。我已经更改了一些代码以简化它(因为您已经在使用jquery)。

演示

var _countries = [{
    "id": "1",
    "Country": "USA"
  },
  {
    "id": "2",
    "Country": "CANADA"
  },
  {
    "id": "3",
    "Country": "GERMANY"
  }
]

var _cities = [{
    "countryID": "1",
    "id": "1",
    "City": "New York"
  },
  {
    "countryID": "1",
    "id": "2",
    "City": "California"
  },
  {
    "countryID": "2",
    "id": "3",
    "City": "Toronto"
  },
  {
    "countryID": "3",
    "id": "4",
    "City": "Berlin"
  },
  {
    "countryID": "3",
    "id": "5",
    "City": "Hamburg"
  },
  {
    "countryID": "3",
    "id": "6",
    "City": "Munich"
  },
]


//Create countries list
var countries = _countries;
var countriesDiv = document.getElementById("_countriesList");
var countriesselectList = document.createElement("select");
countriesselectList.id = "countriesList";
countriesDiv.appendChild(countriesselectList);

//Create and append Countries to the options
for (var i = 0; i < countries.length; i++) {
  var countriesoption = document.createElement("option");
  countriesoption.value = countries[i].id;
  countriesoption.text = countries[i].Country;
  countriesselectList.appendChild(countriesoption);
}

// As we are selecting first option by default, update city list
updateCitiesList();


// update city list on change of country
$('#countriesList').change(function() {
  updateCitiesList();
});


// Update city list function
function updateCitiesList() {


  //Get country ID from country select
  countryID = $("#_countriesList option:selected").attr("value");

  // Filter cities depending on countryID
  var cities = $(_cities).filter(function(i, n) {
    return n.countryID == parseInt(countryID);
  });

  // Clear current select options for citiesList
  $("#citieslist option").remove();

  //Create and append Cities to the options
  for (var i = 0; i < cities.length; i++) {
    {

      var citiesoption = document.createElement("option");
      citiesoption.value = cities[i].id
      citiesoption.text = cities[i].City;
      $("#citieslist").append(citiesoption);

      // Show #citiesList
      $("#citieslist.hidden").removeClass("hidden");

    }
  }

}
.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="_countriesList" class="col s12">
  <!-- Create Countries List Here -->
</div>
<div id="_citiesList" class="col s12">
  <!-- Create Cities List Here -->
  <select id="citieslist" class="hidden">

  </select>
</div>

答案 1 :(得分:1)

我认为countryList的CSS选择器中有一个错字。它应该是$('#_countriesList')。我还发现_citeis而不是_cities还有一个错字。

答案 2 :(得分:1)

您需要在文档“就绪”时运行javascript,以下内容应该可以使用。另外请记住,每次更改国家/地区后,您都会添加一个新的select,我想您要尝试的是替换select

<script type="text/javascript">   
       //Create countries list
       var countries = _countries;
       var countriesDiv = document.getElementById("_countriesList");
       var countriesselectList = document.createElement("select");
       countriesselectList.id = "countriesList";
       countriesDiv.appendChild(countriesselectList);
       //Create and append Countries to the options
       for (var i = 0; i < countries.length; i++) {
           var countriesoption = document.createElement("option");
           countriesoption.value = countries[i].id;
           countriesoption.text = countries[i].Country;
           countriesselectList.appendChild(countriesoption);
       }

       $(function () {
       $('#countriesList').change(function () {
           //populate Cities list
           var cities = _cities;
           var citiesDiv = document.getElementById("_citiesList");
           var citiesselectList = document.createElement("select");
           citiesselectList.id = "citieslist";
           citiesDiv.appendChild(citiesselectList);
           //Create and append Cities to the options
           for (var i = 0; i < cities.length; i++) {
               {
                   if (cities[i].countryID == countriesselectList.value) {
                       var citiesoption = document.createElement("option");
                       citiesoption.value = cities[i].id
                       citiesoption.text = cities[i].City;
                       citiesselectList.appendChild(citiesoption);
                   }
               }
           }
       });
   });

    </script>

这是有关 jquery's $( document ).ready()

答案 3 :(得分:1)

虽然您标记了一个Jquery并使用了它。.对我来说更好在此脚本上使用jquery ..使用jquery可以做到这一点

var _countries =
  [
    { "id": "1", "Country": "USA"},
    { "id": "2", "Country": "CANADA"},
    { "id": "3", "Country": "GERMANY"}
  ]

var _cities =
  [
    { "countryID": "1", "id": "1", "City": "New York" },
    { "countryID": "1", "id": "2", "City": "California" },
    { "countryID": "2", "id": "3", "City": "Toronto" },
    { "countryID": "3", "id": "4", "City": "Berlin" },
    { "countryID": "3", "id": "5", "City": "Hamburg" },
    { "countryID": "3", "id": "6", "City": "Munich" },
  ]
  
 $(document).ready(function(){
    // Append the countries
    // onload loop through the _countries array and append them to #countries select
    $.each(_countries ,function(i){
      $("#countries").append('<option value="'+_countries[i].id+'">'+_countries[i].Country+'</option>');
    });
    
    //Change Event
    $("#countries").on("change" , function(){
       var getVal = $(this).val();    //get the selected value
       $.each(_cities , function(i){   //loop through the _cities 
          if(_cities[i].countryID == getVal){  // if the country id equal the selected value
            $("#cities").html('<option value="'+_cities[i].id+'">'+_cities[i].City+'</option>'); // use html( here to change all the cities select with the new cities list
           }
        });
    }).change();
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="countries"></select>
<select id="cities"></select>

注意:不要忘记将_citeis更改为_cities