Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
93 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)
  )
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...