Calculate JS Value

Asked

Viewed 106 times

0

I have a function for the total calculation.

$('.valor').blur(function(){
    var valor = $("input[name=valor]").val() || 0;
    var descontos = $("input[name=descontos]").val() || 0;
    var juros = $("input[name=juros]").val() || 0;

    valor_cobrado = (parseFloat(valor) - parseFloat(descontos)) + parseFloat(juros);
    $("#valor_cobrado").val(parseFloat(valor_cobrado));
});

The fields have currency mask with comma but the total value is not taking into account the comma.

example 10,50 + 11,00 = 21,00

  • The JS uses the international format, considering the point as decimal separator. If your field is comma formatted, you will need to treat it before doing mathematical operations.

  • Does this code work properly? As it seems to me this occurs: type a value in the field with class value, when you click on another field the action Blur is executed and then forward nothing else occurs unless you click on the input class value and click off again Or am I mistaken? The user will have to have magical powers to do so, ie after everything filled provoke the Blur again

  • is exactly that, as soon as the user enters the value and leaves the field, the total value is calculated. Use the . value for the 3 inputs

  • this means that when you enter the value and exit the other values already exist?

  • No, as he type, he calculates. If he type in the Value field, and leave zeroed in the others, the Total value field will be filled.

  • it’s like I said, after all filled have to click on the value field and provoke the Blur again by clicking off it to perform the math

  • Why Blur again, if you already typed once already calculated.

Show 2 more comments

1 answer

0


JS does not work with a comma, you have to switch to a dot.

valor.replace(',', '.')

Then go back to the window.

valor.replace('.', ',')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.