Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I give an array as options to select element?

Tags:

I have a select element on my HTML page. I want to populate it with an array. as we can give an array as dataprovider to comboBox in action script. I do the following

in HTML...

<table>   <tr>     <td>       <label>Recording Mode:</label>     </td>     <td>       <select id="rec_mode">               </select>     </td>   </tr> </table> 

in javascript...

var videoSrcArr = new Array("option1", "option2", "option3", "option4", "option5"); 

how can I populate rec_mode element when page is loaded with VideoSrcArr? Thanks

like image 462
Sarfraz Ahmed Avatar asked Jan 23 '13 05:01

Sarfraz Ahmed


People also ask

How do you select a value in an array?

You select a value from an array by referring to the index of its element. Array elements (the things inside your array), are numbered/indexed from 0 to length-1 of your array.

Which element is used to select multiple options?

The <select> element has some unique attributes you can use to control it, such as multiple to specify whether multiple options can be selected, and size to specify how many options should be shown at once.

How do you change the specific element of an array?

To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.


1 Answers

I highly recommend you use a format like the following:

var options = [   {     "text"  : "Option 1",     "value" : "Value 1"   },   {     "text"     : "Option 2",     "value"    : "Value 2",     "selected" : true   },   {     "text"  : "Option 3",     "value" : "Value 3"   } ];  var selectBox = document.getElementById('rec_mode');  for(var i = 0, l = options.length; i < l; i++){   var option = options[i];   selectBox.options.add( new Option(option.text, option.value, option.selected) ); } 

You don't run in to the problem of having to select a default option and you can easily generate the options array dynamically.

-- UPDATE --

ES6 version of the above code:

let optionList = document.getElementById('rec_mode').options; let options = [   {     text: 'Option 1',     value: 'Value 1'   },   {     text: 'Option 2',     value: 'Value 2',     selected: true   },   {     text: 'Option 3',     value: 'Value 3'   } ];  options.forEach(option =>   optionList.add(     new Option(option.text, option.value, option.selected)   ) ); 
like image 172
THEtheChad Avatar answered Oct 02 '22 02:10

THEtheChad