your programing

JavaScript-드롭 다운 목록을 배열로 채우기

lovepro 2021. 1. 5. 19:48
반응형

JavaScript-드롭 다운 목록을 배열로 채우기


스크립트에 선언 된 배열이 있습니다.

var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");

드롭 다운 메뉴가 포함 된 양식이 있습니다.

<form id="myForm">
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
</form>

Javascript를 사용하여 나머지 드롭 다운 메뉴를 배열 값으로 어떻게 채웁니까? 따라서 옵션은 "숫자 선택", "1", "2", "3", "4", "5"입니다. . . . . "엔"?


배열 요소를 반복하고 각각에 대해 새 DOM 노드를 만들고이를 개체에 추가해야합니다.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}​

라이브 예


jQuery로도 할 수 있습니다.

var options = ["1", "2", "3", "4", "5"];
$('#select').empty();
$.each(options, function(i, p) {
    $('#select').append($('<option></option>').val(p).html(p));
});

다음과 같이 작동합니다.

var dropdown = document.getElementById("dropdown1");
if (dropdown) {
    for (var i=0; i < month.length;++i){    
        addOption(dropdown, month[i], month[i]);
    }
}

addOption = function(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);  
}

자세한 내용은이 기사를 참조하십시오 :
http://www.plus2net.com/javascript_tutorial/list-adding.php


먼저 DOM에서 드롭 다운 요소를 가져온 다음 배열을 반복하고 다음과 같이 드롭 다운에 새 옵션으로 각 요소를 추가합니다.

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}​

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.


I had the same requirement, I used "Alex Turpin" solution with small corrections as mentioned below.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.text = opt;
    el.value = opt;
    select.add(el);
}​

Corrections because with the appendChild() function is loads when the DOM prepares. So It's not working in old(8 or lesser) IE versions. So with the corrections it's working fine.

Thanks Alex for your solution.

Some notes on differences b/w add() and appendChild()


I found this also works...

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}

["1","2","3","4"].forEach( function(item) { 
   var o = document.createElement("option");
   o.textContext = item;
   document.getElementById("myselect").appendChild(o);
});

<form id="myForm">
<select id="selectNumber">
    <option>Choose a number</option>
    <script>
        var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
        for(i=0; i<myArray.length; i++) {  
            document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
        }
    </script>
</select>
</form>

ReferenceURL : https://stackoverflow.com/questions/9895082/javascript-populate-drop-down-list-with-array

반응형