javascripthtmldropdown

How to create country list using array in javascript? I have total 10 or more select country box in page


How to create country list using array using js? i have total 10 or more select country box in page. i want to create using class name.

var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa" /*, ... */ );

function country() {
  var x = "<option disabled>Select Country</option>";
  
  for (var i = 0; i < country_arr.length; i++) {
    var node = country_arr[i];
    x += "<option value='" + country_arr[i] + "'> " + country_arr[i] + " </option>"
  }

  var countryElement = document.getElementsByClassName('country');
  countryElement.innerHTML = x;
  document.getElementsByClassName("country").innerHTML = x;
}
<div style='text-align:center;'>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
</div>

<script>
  country();
</script>


Solution

  • The code below will cycle through the array, create an option and then appends it to all selects with .country. This solution uses jquery.

    var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa");
    
    country_arr.forEach( function(obj) {
      var temp_country = new Option(obj, obj);
      $(temp_country).html(obj);
      $("select.country").append(temp_country);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <select class="country" name ="country"></select>
    <select class="country" name ="country"></select>
    <select class="country" name ="country"></select> </div>