Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values using each()

I'm trying to return the sum of values ​​every time one of the select is changed. But the sum is always wrong:

$('select').change(function () {
 a = 0;
 $('select').each(function () {
    a += parseInt($('option:selected').val(), 10);
 });
 $('h1 span').html(a);
});

http://jsfiddle.net/vAu3E/

like image 238
marcelo2605 Avatar asked Mar 28 '26 05:03

marcelo2605


2 Answers

$('select').change(function () {
    var a = 0;
    $('select').each(function () {
        a += parseInt(this[this.selectedIndex].value, 10);
    });
    $('h1 span').html(a);
});

JSFiddle

like image 65
Ryan Avatar answered Mar 29 '26 20:03

Ryan


Use this.value (faster than re-getting a jQuery object when you already have it) and declare a so it's not global (I also invoked the handler immediately so your result shows immediately):

$('select').change(function () {
    var a = 0;
    $('select').each(function () {
         a += parseInt(this[this.selectedIndex].value, 10); //originally this.value
    });
    $('h1 span').html(a);
}).change();

http://jsfiddle.net/vAu3E/10/

See comments for potential issues with this.value in versions of IE

like image 26
tymeJV Avatar answered Mar 29 '26 18:03

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!