Sum of values from different divs with the same class

后端 未结 6 1786
囚心锁ツ
囚心锁ツ 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:54

    For

    Elements:

    var sum = 0;
    $('.totalprice').each(function(){
        sum += parseFloat($(this).text());  // Or this.innerHTML, this.innerText
    });
    

    You can see a working example of this here

    For Elements (inputs, checkboxes, etc.):

    var sum = 0;
    $('.totalprice').each(function(){
        sum += parseFloat(this.value);
    });
    

    Alternatively, if you are looking for an integer, you can use the parseInt() function.

    You can see a working example of this here.

提交回复
热议问题