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
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.
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.
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.
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) ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With