I’m trying to find the sum of input values within multiple inputs.
My input form is something like below. Here I want to get input’s data-attribute value for this calculation.
$(document).ready(function() {
const $total = $('#total');
$('.number').blur(function() {
var sum = 0;
$('.number').each(function() {
const data = $(this).data('value');
if (data != "") {
sum += parseFloat(data);
}
});
$total.val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form action="" method="post" id="my-form">
<input type="text" name="a" value="0" class="number" maxlength="2" data-value="0.10">
<input type="text" name="b" value="0" class="number" maxlength="2" data-value="0.20">
<input type="text" name="c" value="0" class="number" maxlength="2" data-value="0.40">
<input type="text" name="d" value="0" class="number" maxlength="2" data-value="1.00">
<input type="text" name="total" id="total" value="0.00 m³" readonly="true">
</form>
Eg:
if name="a" is 1 then name="total" value should be 0.10 m³
if name="a" is 2 then name="total" value should be 0.20 m³
Let say I have input values something like this;
a = 2
b = 1
c = 3
d = 1
Then total should be;
0.10 + 0.10 + 0.20 + 0.40 + 0.40 + 0.40 + 1.00 = 2.60 m³
But it doesn’t work for me. That mean when changing a input I am getting a total of all data-attribute values.
2
Answers
Is not the most jquery code but here is my solution:
You have to reference the current element in the foreach loop as far as I know, as the function’s second argument.
The
.data('...')
or.attr(...)
methods didn’t work as I expected, maybe I’m missing something, so I used the nativegetAttribute('...')
.toFixed(2)
shows only 2 decimal places.Hope it worked!
inputs
value
is parsed as an int.if the input is empty makes to 0.
inputs
data-value
attribute is parsed as a float.using for each to
input field
multiply thevalue
entered by thedata-value
attribute and add it to the runningtotal