简体   繁体   中英

Selecting values in a Drop down menu

I'm new to javascript and have been trying to sum the values from 4 different drop down menu's, however i am unable to get the selected values, here's how my code and the html looks like: 这是来自chrome的HTML图片

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

Here is an example of how you could sum up the values of the selected options of four select-elements. The script will trigger every time a select changes and will alert when their sum is not equal to 6. It uses the HTMLSelectElement.selectedOptions property to get the currently selected option.

 // 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM