简体   繁体   中英

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> 

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM