Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...