how to perform calculations between 4 input, loading page or change value

Asked

Viewed 535 times

1

I have 4 input fields, being:

  1. Cost that already comes with a value
  2. The freight field, which when changed the value must be added to the cost and displayed in total
  3. The discount field, which when changing the value must subtract from the total

Well I don’t know how to do it.

Follow the code with the input.

Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,30'>

<br>
Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos'>

<br>
Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto'>

<br>
Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>

3 answers

3


Your HTML must be changed. Add property onkeyup to the fields encargos and desconto.

Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,35' id="total_pedido">
<br>
Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos' onkeyup='calcular()'>
<br>
Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto' onkeyup='calcular()'>
<br>
Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>

Next we need to define the function calcular:

//É necessário verificar se o campo "total_pedido" já foi renderizado e pode ser referenciado pelo script, 
//por isso é preciso escutar o evento `DOMContentLoaded`.
var total = 0;
document.addEventListener("DOMContentLoaded", function(event) { 
    total = document.getElementById("total_pedido").value;
    //Retiramos a formatação do campo e convertemos em uma string
    total = Number(total.replace(/[.]+/g,"").replace(",","."));
    //A função é executada para preencher o campo com o valor total
    calcular();
});

function calcular() {
    //Obtemos o valor do encargo e desconto
    var encargos = Number(document.getElementById("encargos").value);
    var desconto = Number(document.getElementById("desconto").value);
    var t = total + encargos - desconto;
    //Atualizamos o campo "total_val" com o valor total
    document.getElementById("total_val").value = t.toLocaleString('pt-BR');
}

See working here: https://jsfiddle.net/kmjr5atg/9/

  • There’s only two other things. I noticed that to run I have to put a value on the freight or discount, have to run even if they are blank? ie already load the page running. 2º and possible to write the total value in the default 1.000,00?

  • @Hugoborges, yes, has. I changed the answer, see if it is the intended.

  • @Hugoborges added the formatted value in the reply example, see how it works: https://jsfiddle.net/kmjr5atg/4/

  • that’s right, but instead of appearing the R$ in total I need the value only formatted in en 1.000,00.

  • @Hugoborges just remove the string "RS" in the above code. I updated the answer.

  • but it doesn’t get formatted in 1,000.00 standard

  • @Hugoborges just change the line where we have document.getElementById("total_val").value = t; for document.getElementById("total_val").value = t.toLocaleString();. See, I posted in response this option.

  • friend forgive my ignorance hahahah but it did not work with me. The number of the total is like this: 5022.35 and I need it to stay like this: 5.022,35

  • @Hugoborges but it’s like this, review the answer I gave and see here the code I posted above working: https://jsfiddle.net/kmjr5atg/9/

  • Strange, here really isn’t working. Take a look at this print I took. http://s11.postimg.org/ykhnwg6qb/Captura_de_Tela_2016_02_24_s_13_14_19.png. Note that the valar is not formatted with . and ,

  • friend noticed that the error occurs only in safari, strange. But anyway thank you very much for the solution. Just one more question, it is possible to make that when changing the total_val the system informs the discount?

  • @Hugoborges has yes, see here it works: https://jsfiddle.net/kmjr5atg/11/

  • very good, now has to pass the discount to %. there will be everything 100% :)

Show 8 more comments

2

Explaining the code below;

  1. Through the ID, captured the references of the HTML;
  2. Added an event for the elements desconto and frete, so that these will perform the function calcular() whenever a key pressed is released;
  3. We define the function calcular, that transforms the values of inputs into numbers through the builder Number and makes the calculation (total = custo + frete - desconto);
  4. Finally, we attribute to value of the element total the calculation made, formatting your presentation to 'pt-BR' with the method toLocaleString

var frete = document.getElementById("encargos");
var desconto = document.getElementById("desconto");
var total = document.getElementById("total_val");
var custo = document.getElementById("total_pedido");

/*Criando eventos para executarem a função calcular sempre que uma tecla for pressionada*/
desconto.addEventListener("keyup", function() {
  calcular();
});

frete.addEventListener("keyup", function() {
  calcular();
});

/*Função calcular; converte os valores dos inputs para float e então calcula (total = custo + frete - desconto)*/
function calcular() {
  var valorTotal = Number(custo.value) + Number(frete.value) - Number(desconto.value);
  total.value = valorTotal.toLocaleString('pt-BR');
}
Custo
<input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5000.30'>

<br>Frete
<input type='text' class='form_campos calc' id='encargos' name='encargos'>

<br>Desconto
<input type='text' class='form_campos calc' id='desconto' name='desconto'>

<br>Total
<input type='text' class='form_campos calc2' id='total_val' name='total_val'>

References

  • 1

    Okay, but there are some things that need to be changed. I noticed that it only works if I inform a value for freight and discount, but I need it to work if no value is informed. It has as?

  • I will update the answer, I am without much time now. It is possible to update the calculate function. I suggest starting both fields with value 0. It was also necessary to format the cost field because the value "5,000.03" cannot be converted to float without treatment before. Soon I update the reply with both information

  • OK I’ll be waiting

  • Code has been updated to only work with values reported

-1

    //obtenho o valor dos campos
    var vtotal = $('#total_pedido').val();
    var vfrete = $('#encargos').val();
    var desconto= $('#desconto').val();

    //efetuo o calculo que será exibido no ultimo input
    vtotal = ((vtotal+vfrete)-desconto);
    //escrevo o resultado no ultimo input
    $('#total_val').val(vtotal);

   // lembrando que as tags dessa pergunta mencionam javascript E JQuery
  • 2

    how I call the function in input?

  • Could explain what this code does?

  • To call the function in the input create a javascript function with the name you want, use the input event to call the function. For example, if you want to call the name function calculate when the user takes the focus of an input you put it in the onBlur="javascript:calculate();"input. To the friend who asked me to explain what the job is. In the first three lines I get the input value, in the fourth I calculate and write the result in the last input. Obviously missing due treatment when there are null fields, as well as conversions with parseFloat().

Browser other questions tagged

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