Josh
Josh

Reputation: 15

How to find the sum of multiple select's selected options?

<select multiple name="item" style="width: 225px;" action="post" id="mySelect" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="10">One
<option value="20">Two
<option value="30">Three
<option value="40">Four
<option value="50">Five
<option value="60">Six
</select>

<p>Total: <b><span id="selectedValue"></span></b></p>

I'm trying to get the total price displayed if multiple items are selected but it doesn't seem to be working for me. It's probably something simple but I can't get it. Any help greatly appreciated.

Upvotes: 1

Views: 863

Answers (2)

Ram
Ram

Reputation: 144669

value property stores the last selected option's value, since you have a multiple select element, you can iterate through the selectedOptions collection of the HTMLSelectElement object:

document.getElementById('mySelect').addEventListener('change', function() {
    var total = 0,
        selected = this.selectedOptions,
        l = selected.length;

    for (var i = 0; i < l; i++) {
       total += parseInt(selected[i].value, 10);
    }

    // ...       
});

http://jsfiddle.net/qoft7mre/

Upvotes: 2

Gurkan İlleez
Gurkan İlleez

Reputation: 1573

onChange="document.getElementById('selectedValue').innerHTML = parseInt(document.getElementById('selectedValue').innerHTML || 0) + parseInt(this.value);"

This is not what you really want but you can sum like this.

Upvotes: 0

Related Questions