简体   繁体   中英

How do you get this function to read more than one selection?

I am using this function to output a selected option to an alert from a scrolling list:

var topping = "";
            function toppingTotal() {
                var top = document.getElementById('topList');
                if (top.selectedIndex > 0) {
                    topping = topping + "Toppings: " + top.options[top.selectedIndex].text;
                    return topping;
                }
            }

Code works fine, but how do I get this to output multiple selections?

I am assuming you have a select with attribute multiple . You can try this

for (var i = 0; i < top.options.length; i++) {
    if (top.options[i].selected) {
        topping  += top.options[i].text + " ";
    }
}
return topping;

For reference - http://plnkr.co/edit/j2PgGy6FJsuLvKSxSOIZ?p=preview

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