Javascript store <select> dropdown values wi

2019-06-02 01:00发布

问题:

I'm wondering if it's possible to store the selected values from a <select>in a JS array.

What I finally need to do is calculate the highest 6 values out of around 10 dropdowns, which I think I can do by using the JS Math.max() function.

Help is greatly appreciated.

Here is some sample code:

<? 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>....

回答1:

Do something like this (JQuery):

var selected = new Array();
            $('.points option:selected').each(function() {
                selected.push($(this).val());
            });


回答2:

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.
});​

This assumes that all the selects on the page should be included. If that isn't the case, then you should use document.getElementsByClassName or a similar, more appropriate selector instead.

Demo



回答3:

Try this:

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"