3
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>
Sam is great. But parseint will generate wrong calculations. Maybe parseFloat would be better.
– aa_sp
True! It will work if the value has no pennies. I’ll take a look here. Obg!
– Sam
Now resolved!
– Sam
Man, THANK YOU. I’m a javascript beginner and you solved my problem! It worked perfectly.
– Sallazar