最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sum values using each() - Stack Overflow

programmeradmin3浏览0评论

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

/

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

Share Improve this question edited Oct 28, 2018 at 13:53 Cœur 38.7k26 gold badges203 silver badges277 bronze badges asked Jun 20, 2014 at 15:09 marcelo2605marcelo2605 2,7945 gold badges31 silver badges58 bronze badges 1
  • var sum = $("select option:selected").toArray().reduce(function(sum, val) { return sum+val; }, 0); – cookie monster Commented Jun 20, 2014 at 15:24
Add a ment  | 

6 Answers 6

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

JSFiddle

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

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

Using sum plugin , you will have :

$('select').change(function () {
    $('h1 span').html($('option:selected').sum());
});

FIDDLE : http://jsfiddle/abdennour/vAu3E/18/

NOTE

You use val method since your element is option tag. But , If It is a sum of DIV content elements for example , You must use html method instead of val :

So , the sum plugin still useful :

   $('div.operators').sum('html');

I suggest this:

$("select").on("change", function(){
    var a = 0;
    $("select").each(function(){
        a += parseInt($(this).val());
    });
    $('h1 span').html(a);
});

fiddle

Obviously the result is correct, because you have to substitute "option:selected" with this:

a += parseInt($(this).val(), 10);

If you put "option:selected" the selector is the first selector, instead with $(this) you get the value of each select...

Hope that this ment help you... Bye

There's an alternative to parseInt; prepending a + will convert a 'numeric` string into a number:

$('select').change(function () {
    var a = 0;
    $('select').each(function () {
        a += +this.value;
    });
    $('h1 span').html(a);
});

WORKING JSFIDDLE DEMO

发布评论

评论列表(0)

  1. 暂无评论