0

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>
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 4
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Andreas Dec 08 '18 at 13:36

2 Answers2

1

You nee to iterate over the HTMLCollection elements you get with document.getElementsByClassName("country"):

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>"
  }
  
  let list = document.getElementsByClassName("country");
  for (let item of list) {
    item.innerHTML = x;
  }

}

country();
<div style='text-align:center;'>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
  <select class="country" name="country"></select>
</div>
Zim
  • 1,457
  • 1
  • 10
  • 21
1

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>
Oliver Trampleasure
  • 3,293
  • 1
  • 10
  • 25