I cannot place function on inputs containing masks

Asked

Viewed 139 times

3

campos do formulario

Guys, I have these three fields in a product registration system. The first is the cost price, the second the profit over the first and last the selling value of the product. What happens is that to calculate that selling value i created a javascript function that calculates over the first two fields and displays the result in the third, see below:

function calcular() {
            var custo = parseInt(document.getElementById("valor_custo").value);
            var lucro = parseInt(document.getElementById("lucro_sugerido").value);
            var input = document.getElementById("valor_venda");
            var result = document.createAttribute("value");
            result.value = custo + (custo * (lucro/100));

            input.setAttributeNode(result);
        }

That’s where the problem begins. The function works perfectly, but I put masks on the fields as you can see in the image, and the function just stopped working with the masks, it only works with the numbers, but when I put the masks on it stops working. If you could help me I’d be very grateful!

See the full code:

//jquery para as mascaras de R$

$("#valor_custo").maskMoney({
                prefix: "R$",
                decimal: ",",
                thousands: "."
            });
            $("#valor_venda").maskMoney({
                prefix: "R$",
                decimal: ",",
                thousands: "."
            });
            
//jquery para a mascara de %
            
$("#lucro_sugerido").mask("00%");

//função js para retornar o valor de venda

function calcular() {
            var custo = parseInt(document.getElementById("valor_custo").value);
            var lucro = parseInt(document.getElementById("lucro_sugerido").value);
            var input = document.getElementById("valor_venda");
            var result = document.createAttribute("value");
            result.value = custo + (custo * (lucro/100));

            input.setAttributeNode(result);
        }
<!-- lembrando que isso está dentro de um <form> -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>
<script src="https://cdn.rawgit.com/plentz/jquery-maskmoney/master/dist/jquery.maskMoney.min.js"></script>

<div class="vendas">
  <h4>Preço</h4>
  <input type="text" name="valor_custo" id="valor_custo" placeholder="Valor de custo*" required>
  <input type="text" name="lucro_sugerido" id="lucro_sugerido" value="50" placeholder="Lucro sugerido*" required>
  <input type="number" name="valor_venda" id="valor_venda" onfocus="calcular()" placeholder="Valor de venda*" readonly required>
</div>

1 answer

2


There are some issues that need to be fixed in the code. The type="number" of the sales value input will not accept mask because it does not accept anything other than number. Change to type="text" even.

The mask is also invalidating the calculation because of R$ and of %, and it is also necessary to remove the points of the thousands, when there are, and replace the comma of the decimals by the point.

What you should do is remove what is not a number of values and remove all points and then replace the comma by a dot. For this you can use a regular expression replace in the value of the first field:

var custo = parseInt(document.getElementById("valor_custo").value.replace(/[R$\.]/g, "").replace(",", "."));

The expression /[R$\.]/g will remove R, $ and the dot. Then replace another to the comma.

At the value of the second field you can use a simple replace to remove the %:

var lucro = document.getElementById("lucro_sugerido").value.replace("%", "");

You don’t have to use parseInt in the variable lucro because you will not use this value for sum or subtraction.

The parseInt will also ignore the pennies, so switch to parseFloat only in the variable custo:

var custo = parseFloat(document.getElementById("valor_custo").value.replace(/[R$\.]/g, "").replace(",", "."));

Another problem is that if there are pennies, the mask will multiply the value by 100 because it adds two zeros at the end of the value. To fix this you need to use two more methods in the final value: .toFixed(2) and replace it with a semicolon:

(custo + (custo * (lucro/100))).toFixed(2).replace(".", ",");

Another thing is that you don’t need to create attribute node, just put elemento.value = valor; that the value is already included in the field.

Behold:

//jquery para as mascaras de R$

$("#valor_custo").maskMoney({
                prefix: "R$",
                decimal: ",",
                thousands: "."
            });
            $("#valor_venda").maskMoney({
                prefix: "R$",
                decimal: ",",
                thousands: "."
            });
            
//jquery para a mascara de %
            
$("#lucro_sugerido").mask("00%");

//função js para retornar o valor de venda

function calcular() {
            var custo = parseFloat(document.getElementById("valor_custo").value.replace(/[R$\.]/g, "").replace(",", "."));
            var lucro = document.getElementById("lucro_sugerido").value.replace("%", "");
            var input = document.getElementById("valor_venda");
//            var result = document.createAttribute("value");
//            result.value = custo + (custo * (lucro/100));
//            input.setAttributeNode(result);
            input.value = (custo + (custo * (lucro/100))).toFixed(2).replace(".", ",");
        }
<!-- lembrando que isso está dentro de um <form> -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>
<script src="https://cdn.rawgit.com/plentz/jquery-maskmoney/master/dist/jquery.maskMoney.min.js"></script>

<div class="vendas">
  <h4>Preço</h4>
  <input type="text" name="valor_custo" id="valor_custo" placeholder="Valor de custo*" required>
  <input type="text" name="lucro_sugerido" id="lucro_sugerido" value="50" placeholder="Lucro sugerido*" required>
  <input type="text" name="valor_venda" id="valor_venda" onfocus="calcular()" placeholder="Valor de venda*" readonly required>
</div>

  • 2

    Sam is great. But parseint will generate wrong calculations. Maybe parseFloat would be better.

  • True! It will work if the value has no pennies. I’ll take a look here. Obg!

  • Now resolved!

  • Man, THANK YOU. I’m a javascript beginner and you solved my problem! It worked perfectly.

Browser other questions tagged

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