Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate the options of a select element in javascript

The code:

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++; } 

I'm trying to get options populated by this way but its not coming all right as I don't know how to populate the options from an array in JS. Do I even have to use the loop or can I just assign the langArray to some property of select element and every thing will be up and running?

like image 820
samach Avatar asked Jul 06 '11 18:07

samach


People also ask

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }

How do I change an HTML selected option using JavaScript?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.

How do I create a dynamic selection in HTML?

var select = $("<select></select>"); var opt = $("<option></option"); opt. val("1"); opt. html("Option 1"); select.


1 Answers

You can create the option inside the loop;

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 
like image 84
Ibu Avatar answered Sep 18 '22 17:09

Ibu