Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Multiple select amount

I have different selects with different values in them. How can I get total amount of those values?

For example I have

<select class="total">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
<select class="total">
    <option>2</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

And if I select from the first select 1 and from the second 2 I want to get 3 as result.

http://jsfiddle.net/vQ8Bm/

Upvotes: 1

Views: 74

Answers (5)

nickaknudson
nickaknudson

Reputation: 4807

You should look through the selected elements and convert each to an integer, then add them.

var sum = 0;
$('.total :selected').each(function () {
    sum += parseInt($(this).text());
});

UPDATE

Inside the select change event

$('.total').change(function () {
    var sum = 0;
    $('.total :selected').each(function () {
        sum += parseInt($(this).text());
    });
});

Upvotes: 2

jAndy
jAndy

Reputation: 236122

Just in case, a vanilla-js solution

var map = Array.prototype.map;

var res = map.call(document.getElementsByClassName('total'), function( select ) {
    return select.value;
}).reduce(function( a, b ) {
    return +a + +b;
});

alert(res);

demo: http://jsfiddle.net/vQ8Bm/6/

Upvotes: 4

VisioN
VisioN

Reputation: 145458

$(".total").change(function() {
    var sum = $(".total").map(function() {
        return +this.value;
    }).get().reduce(function(a, b) {
        return a + b;
    }, 0);
    console.log(sum);
});

DEMO: http://jsfiddle.net/vQ8Bm/4/

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359966

Get the sum of the values across multiple <select>s:

var total = 0;
$('select.total').each(function () {
    total += parseInt($(this).val(), 10);
});

console.log(total);

Upvotes: 3

adeneo
adeneo

Reputation: 318312

$(document).ready(function () {
    $('.total').on('change', function () {
        var sum = 0;
        $('.total').each(function () {
            sum += parseInt(this.value, 10);
        });
        alert(sum);
    });
});

FIDDLE

Upvotes: 4

Related Questions