0

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?

2 Answers 2

1

Try

function calculateVersements() {
    var versement_each = 0;
    $('.versement_each').each(function () {
        versement_each += parseFloat(this.value) || 0;

    });
    console.log(versement_each.toFixed(2));
}
Sign up to request clarification or add additional context in comments.

2 Comments

This code is working good for now! If I understand it correctly, the || 0 is only a condition to avoid the value = 0 ?
The || 0 is used so that the NaN values can be escaped
1

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);

3 Comments

versement_each += newValue is the way to go, so the first is not needed at all. Also instead of $(this).val() -> this.value is much... JS?
@RokoC.Buljan That's a very good point about this.value. I included the first option simply because some visitors might not be familiar with compound assignment, and I wanted to demonstrate that they are equivalent.
I think this way could actually works good, but it seems only to "stack" all the data so I could have the result 03303300

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.