Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input array sum with jQuery

Tags:

html

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

like image 527
DorienCragen Avatar asked Oct 07 '13 09:10

DorienCragen


2 Answers

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:

  • $.each()
  • parseFloat()
like image 125
Lix Avatar answered Nov 19 '22 14:11

Lix


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);
});
like image 7
SridharVenkat Avatar answered Nov 19 '22 16:11

SridharVenkat