Sum of values from different divs with the same class

后端 未结 6 1789
囚心锁ツ
囚心锁ツ 2020-12-13 18:15

I am loading dynamically divs that have a .totalprice class. At the end, I would like to sum of the values from all of the .totalprice.

6条回答
  •  一个人的身影
    2020-12-13 18:51

    Unless you're absolutely certain about the value of your content, you will not be able to use parseFloat out of the box.

    You need to be sure to handle:

    • Excessive Whitespace
    • Leading $
    • Blanks
    • Unexpected Strings

    Take a look:

    $1.25
    0.25
    $3.00
    2.50
    $0.01

    The following will handle all cases:

    var sum = 0;
    
    $(".totalprice").each(function() {
        var val = $.trim( $(this).text() );
    
        if ( val ) {
            val = parseFloat( val.replace( /^\$/, "" ) );
    
            sum += !isNaN( val ) ? val : 0;
        }
    });
    
    console.log( sum );
    

    See also: http://jsfiddle.net/rwaldron/hfA5V/

提交回复
热议问题