0

How could I use an array to fill the options in a scrolling list. eg/

<B>Select some fruit:</B> <BR>
<SELECT NAME="Morefruit" SIZE="4" MULTIPLE >
<OPTION SELECTED> Apples
<OPTION> Bananas
<OPTION> Oranges
<OPTION> Watermelon    
</SELECT>

2 Answers2

0

You can try adding an id to your list and use jQuery append function, and a for loop.

Something like:

var list = [];

for(var i = 0;i<list.length;i++) {
 $.('#myList').append("<option>"+list[i]+"</option>");
}
0

Here's a quick and dirty way to take an array, map its values to HTML options, and assign it to the select all in one statement.

What I like about this approach is that the options are added to the select element once as opposed to adding each option one at a time. You don't want to manipulate the DOM more than necessary and so one DOM operation (innerHTML) lets you avoid most of the performance penalty. I also like the use of the Array object's map method here, because you're taking a list of data and turning it into a list of HTML options using a simple mapping function. Finally, the Array joining converts the list to a string of HTML so that it can be added to the select element.

var select = document.getElementById("select");
var options = ["Apples", "Oranges", "Banaynays"];

select.innerHTML = options.map(function(option) {
  return "<option>" + option + "</option>";
}).join("");
<select id="select"></select>
Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50