Javascript 我怎样才能给一个数组作为选择元素的选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14473207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:54:18  来源:igfitidea点击:

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

javascripthtml

提问by Sarfraz Ahmed

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

我的 HTML 页面上有一个 select 元素。我想用一个数组填充它。因为我们可以在动作脚本中为组合框提供一个数组作为数据提供者。我做以下

in HTML...

在 HTML...

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

in javascript...

在 JavaScript 中...

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

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

当使用 VideoSrcArr 加载页面时,如何填充 rec_mode 元素?谢谢

回答by THEtheChad

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:

以上代码的ES6版本:

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

回答by ameya rote

I would recommend to use object instead of array it will be of great helpful and in respected manner with standards. The reason is WE can index into the object by the "key" and get the "value" . To display contents and resetting them you can follow this NOTES

我建议使用对象而不是数组,这将非常有帮助,并且符合标准。原因是 WE 可以通过“键”索引到对象并获得“值”。要显示内容并重置它们,您可以按照此 注意事项

CHECK HERE

在这里检查

<!DOCTYPE html>
<html>
<body>
<table>
  <tr>
    <td>
      <label>Recording Mode:</label>
    </td>
    <td>
      <select id="rec_mode">        
      </select>
    </td>
  </tr>
</table>
</body>
<script>
var myobject = {
    ValueA : 'Text A',
    ValueB : 'Text B',
    ValueC : 'Text C'
};
var select = document.getElementById("rec_mode");
for(index in myobject) {
    select.options[select.options.length] = new Option(myobject[index], index);
}

</script>
</html>

回答by JDev

This is the simplest way to populate comboBox with an array.

这是用数组填充组合框的最简单方法。

var j = new Array("option1","option2","option3","option4","option5"),    
var options = '';

for (var i = 0; i < j.length; i++) {
   options += '<option value="' + j[i]+ '">' + j[i] + '</option>';
}
$("#rec_mode").html(options);

回答by dmk

You can do this:

你可以这样做:

var videoSrcArr = new Array("option1","option2","option3","option4","option5"),
    selectEl = document.getElementById('rec_mode');


for(var i = 0; i < videoSrcArr.length; i++){
    selectEl.options.add(new Option(videoSrcArr[i], videoSrcArr[i]));
}                              

回答by Parul

This is the best way you can get array values in combo box

这是在组合框中获取数组值的最佳方式

var states = new Array();
states['India'] = new Array('Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Goa','Gujarat','Haryana','Himachal Pradesh','Jammu and Kashmir','Jharkhand','Karnataka','Kerala','Madhya Pradesh','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Odisha','Punjab','Rajasthan','Sikkim','Tamil Nadu','Telangana','Tripura','Uttar Pradesh','Uttarakhand','WestBengal','Andaman and Nicobar Islands','Chandigarh','Dadra and Nagar Haveli','Daman and Diu','Lakshadweep','Puducherry'); 

function setStates() {
 var newOptions=states['India'];
 var newValues=states['India'];
 selectField = document.getElementById("state");
 selectField.options.length = 0;
 for (i=0; i<newOptions.length; i++) 
 {
 selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
 }
}
<body  onload="setStates();"
<label>State :</label>
<select style="width:auto;" name="state" id="state">
<option value="">Please select a Country</option>
</select><br>