CodexVarg
CodexVarg

Reputation: 510

input array sum with jQuery

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

Upvotes: 5

Views: 13910

Answers (5)

Lix
Lix

Reputation: 47966

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:

Upvotes: 8

SridharVenkat
SridharVenkat

Reputation: 656

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

Upvotes: 7

you can do it like this

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

Upvotes: 2

Anton
Anton

Reputation: 32581

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

DEMO

Upvotes: 3

letiagoalves
letiagoalves

Reputation: 11302

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

Upvotes: 0

Related Questions