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
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()
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With