Javascript 在数组中存储<选择>下拉值

Javascript store <select> dropdown values within array

本文关键字:选择 数组 存储 Javascript      更新时间:2023-09-26

我想知道是否可以将<select>中的选定值存储在JS数组中。

我最终需要做的是计算大约 6 个下拉列表中最高的 10 个值,我认为我可以使用 JS Math.max() 函数来完成。

非常感谢帮助。

下面是一些示例代码:

<? while($subjects = mysql_fetch_array($query)) { ?>
<select class="points">
<optgroup label="<?=$subjects['name']?>">
  <option value="100">A1</option>
  <option value="90">A2</option>
  <option value="85">B1</option>
  <option value="80">B2</option>
  <option value="75">B3</option>
</optgroup>
</select>
<? } ?>
<script>....

做这样的事情(JQuery):

var selected = new Array();
            $('.points option:selected').each(function() {
                selected.push($(this).val());
            });
var selects = [].slice.apply(document.getElementsByTagName('select'));
selects.forEach(function (elem, i){
    var value = elem.options[elem.selectedIndex].value;
    //Do something with this value. Push it to an array, perhaps.
});​

这假定应包含页面上的所有select。如果不是这种情况,那么您应该改用document.getElementsByClassName或类似的、更合适的选择器。

演示

试试这个:

var selectValues = [];
var selectNodeList = document.getElementsByClassName("points");
for (var i = 0; i < selectNodeList.length; i++) {
    selectValues.push(selectNodeList[i].value)
}
// selectValues array now stores values of all <select> lists with class "points"