Reputation: 372
I need to calcultate the value of dynamics price field and save it to my logs with jQuery.
The user can add fields by pressin a button. This part of the code is already working with auto-increment, etc.
Here is my code.
<input name="value_1" min="0" class="versement_each" id="booking_1" autocomplete="off" readonly="readonly" type="text"/></div>
I am using the class versement_each to start my loop.
function calculateVersements()
{
var versement_each = 0;
$('.versement_each').each(function()
{
versement_each = parseFloat($(this).val() + versement_each).toFixed(2);
});
console.log(versement_each);
}
My code is woking at like 50% since it does calculate, but only takes the first value.
Also, can you tell my if my way to transform my output data to 00.00 is OK?
Upvotes: 0
Views: 6569
Reputation: 149000
Try something like this:
$('.versement_each').each(function()
{
versement_each = versement_each + parseFloat(this.value);
});
Or even better:
$('.versement_each').each(function()
{
versement_each += parseFloat(this.value);
});
And only after you've computed the sum, convert it back to a string:
versement_each = versement_each.toFixed(2);
Upvotes: 1
Reputation: 388316
Try
function calculateVersements() {
var versement_each = 0;
$('.versement_each').each(function () {
versement_each += parseFloat(this.value) || 0;
});
console.log(versement_each.toFixed(2));
}
Upvotes: 1