2011-07-06 7 views
17

에 코드 select 요소의 옵션을 채우는 방법 :이 방법으로 채워 옵션을 얻으려고하지만 내가 채우는 방법을 모르는 권리로 모든 오지 않을자바 스크립트

var newSelect=document.createElement('select'); 
index=0; 
var optn = document.createElement("option"); 

//langArray is an array that contains different items..the size 
//is not fixed for this array. 

for(element in langArray) 
{ 
    //Now i want to assign each item in langArray to each option tag 
    //will it be sumthng like "optn.options[index]=new Option("Sports", "sportsvalue", true, false); 
    //optn.accept(langArray[0]); 
    index++; 
} 

을 JS의 배열에있는 옵션. 루프를 사용해야할까요? 아니면 langArray를 select 요소의 일부 속성에 할당하면 모든 것이 실행되고 실행됩니까?

답변

27

루프 내에 옵션을 만들 수 있습니다.

for(element in langArray) 
{ 
    var opt = document.createElement("option"); 
    opt.value= index; 
    opt.innerHTML = element; // whatever property it has 

    // then append it to the select element 
    newSelect.appendChild(opt); 
    index++; 
} 

// then append the select to an element in the dom 
+1

고맙습니다. lbu ... 내 생각에 'newSelect.appendChild (opt)'가 아닐까요? 'newSelect.append (opt);'나를 위해 일하지 않았다 !! – samach

+0

고마워요. – Ibu

11

당신은, 루프 내부에 option 요소를 만드는 데 필요한 속성과 텍스트를 설정하고 select 요소에 추가합니다

var langArray = [ 
    {value: "val1", text: "text 1"}, 
    {value: "val2", text: "text 2"} 
]; 
:

var select = document.createElement('select'), 
    option, 
    i = 0, 
    il = langArray.length; 

for (; i < il; i += 1) { 
    option = document.createElement('option'); 
    option.setAttribute('value', langArray[i].value); 
    option.appendChild(document.createTextNode(langArray[i].text)); 
    select.appendChild(option); 
} 

이것은 당신의 langArray 이런 식으로 뭔가를 보이는 것으로 가정

배열과 일치하도록 코드를 조정해야합니다.