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
.
If you do this very often throughout your code, it is recommended to put it in a nice reusable function
function removeComma(x)
{
if (x)
{
if (x.length > 0)
{
return x.replace(/,/g,'');
}
}
}
function sum_class(list,source)
{
// source can be text for non input DOM elements or value for text inputs
var total = 0;
$(list).each(function() {
if (source == 'text')
{
total += parseFloat(removeComma($(this).text()));
}
else
{
total += parseFloat(removeComma($(this).val()));
}
});
return total;
}
Keep in mind that both functions use variables I've name to what makes sense to me, you can rename them to what you understand works better for you, like the name of the function sum_class, is not referring to an OOP class but the the purpose of the function which is to return the total of values from elements that belong to the same class.