5

Hello I have unknown quantity of inputs with array name and class

<input type="hidden" name="hidden[1]" class="sum" value="31">
<input type="hidden" name="hidden[2]" class="sum" value="21">
<input type="hidden" name="hidden[3]" class="sum" value="321">
<input type="hidden" name="hidden[4]" class="sum" value="-31">
<input type="hidden" name="hidden[5]" class="sum" value="31.12">
<input type="hidden" name="hidden[6]" class="sum" value="0">

Question is how sum all values of those fields what i try is to use .each() and getElementByClassName but this wont work

1
  • 2
    could you show your not working code..? Commented Oct 7, 2013 at 9:18

5 Answers 5

8

Iterate over the matched elements and add their values together:

var total = 0;
$( ".sum" ).each( function(){
  total += parseFloat( $( this ).val() ) || 0;
});

I'm using $.each() to iterate over all items matching the .sum class, and then extracting the value attribute with .val(). Once we have that value, we need to make sure that it is numerical so I've used parseFloat(). If parseFloat() returns a falsy value, 0 will be used.

References:

Sign up to request clarification or add additional context in comments.

2 Comments

parseInt(31.12).. would be 31, but its 31.12..?
I'd also use $(this).val() or this.value instead of attr.
7

I tried using the each, it worked for me. Check if you used parseFloat...
If you have 'sum' as a class to define all the elements that must be calculated, below code should work....

$(document).ready(function () {
    var total = 0;
    $('.sum').each(function (index, element) {
        total = total + parseFloat($(element).val());
    });
    alert(total);
});

Comments

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

DEMO

1 Comment

+1 for being the only one who correctly used parseFloat instead of parseInt
2

you can do it like this

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

Comments

0

Using each jQuery function to iterate input.sum elements will be enough.

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

Working demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.