在下拉菜单中选择值

时间:2020-06-15 17:22:38

标签: javascript

我是javascript新手,一直在尝试对4个不同的下拉菜单中的值求和,但是我无法获取所选的值,这就是我的代码和html的样子: Here is a picture of the HTML from chrome

var el = document.getElementsByTagName("select");
var elVal = el.options[el.selectedIndex].value


for(var i=0; i<el.length;i++){
    el[i].onchange = function(){
    var sum = 0;
    sum += parseInt(elVal);
        if(sum!=6){
            alert("blabla");    
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这里是一个示例,您可以对四个选择元素的所选选项的值求和。该脚本将在每次选择更改时触发,并在它们的总和不等于6时发出警报。它使用HTMLSelectElement.selectedOptions属性获取当前选择的选项。

// convert nodeList into array to be able to use reduce()
const selects = [...document.getElementsByTagName("select")];

// delegate eventHandling to a common ancestor of our select-elements
document.onchange = () => {
  // sum up the selected options by iterating over the select-elements
  const sum = selects.reduce((total, select) => {
    return total + Number(select.selectedOptions[0].value);
  }, 0);
  
  if (sum !== 6) alert('foo');
};
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>