Shawn
Shawn

Reputation: 941

how to make a javascript array be the choices in an <option> tag

title is self explanatory i think..

is there anyway to make a list of about 300 items in an array be the choices in

<option>ARRAY DATA</option></select>

Upvotes: 0

Views: 2061

Answers (2)

erickb
erickb

Reputation: 6309

Try this:

var s = document.getElementById('id_of_select_tag');
var ar = [1,2,3];
for(var i=0; i<ar.length; i++) {
  var option = document.createElement('option');
  option.text = ar[i];
  option.value = ar[i];
  s.options[s.options.length] = option;
}

http://jsfiddle.net/erick/9Dj3j/3

Upvotes: 4

user
user

Reputation: 6947

Does the JavaScript array really have to be generated from the choices in the <select>? Particularly, can't it be the other way around?

If you can get away with generating the contents of the list from the array, all you'll need to do is iterate over the array and output the list elements. I'm pretty sure you could even do that without even touching document.write() and its kin, but JavaScript DOM manipulation is far from what I know best.

Upvotes: 0

Related Questions