Reputation: 25
Im fighting with my code for a couple of hours, and no success. I want to sum all values from data-price but I am constantly getting NaN. My code "looks" correctly created, not understand why it do not work. Any help will be appreciable.
$("#sub").click(function() {
var sum = 0;
$('#form input').each(function() {
sum += $(this).data('price');
});
alert(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" name="make" value="0">
<input type="hidden" name="got" value="" data-price='10'>
<input type="hidden" name="get" value="" data-price='20'>
<button id="sub">submit</button>
</form>
Upvotes: 2
Views: 355
Reputation: 337560
The issue is because the first input has no data-price
attribute, therefore undefined
is returned and causes an error in the calculation.
To fix this you can coerce a null/missing value to 0
before you add it to the sum
:
$("#sub").click(function() {
var sum = 0;
$('#form input').each(function() {
sum += $(this).data('price') || 0; // note the change on this line
});
console.log(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" name="make" value="0">
<input type="hidden" name="got" value="" data-price='10'>
<input type="hidden" name="get" value="" data-price='20'>
<button id="sub">submit</button>
</form>
Alternatively you could put a class on only the desired input
elements whose values you want to total and select by that instead.
Upvotes: 3