Showing data as you type

3

I need to show two information when the user enters the commission amount, in case the information I should show would be IR and Valor líquido .

For example, if the user types 1.200,00 , the IR label would appear 18,00% (1,200 x 1,5%) and label Valor líquido net total (1,200 - 18) that would give% with%.

I believe that I would have to put some function in javascript, but I am lay with this language, or if there is any other way, all help will be welcome.

Obs. the intention is only to show the two values IR and Net Value without needing to save anything, because what I need to save even would be the value of the commission.

My code:

<form method="post"action="processa.php">
    <label>Valor comissão:</label>
    <input type="text" name="valor_comissao">

    <label>IR:</label>
    <input type="text">

    <label>Valor Líquido:</label>
    <input type="text">

    <button type="submit">Enviar</button>
</form>
    
asked by anonymous 26.09.2017 / 14:02

1 answer

4

You can do this using keyup in the input like this:

const [valor, ir, liquido] = [...document.querySelectorAll('form input')];

/* ou em browsers antigos:
var inputs = document.querySelectorAll('form input');
var valor = inputs[0];
var ir = inputs[1];
var liquido = inputs[2];
*/

function formatar$(nr) {
  return nr.toLocaleString('pt-BR');
}

valor.addEventListener('keyup', function() {
  var nr = Number(this.value);
  var _ir = nr * 1.5 / 100;
  ir.value = _ir + '%';
  liquido.value = formatar$(nr - _ir);
});
<form method="post" action="processa.php">
  <label>Valor comissão:</label>
  <input type="text" name="valor_comissao">

  <label>IR:</label>
  <input type="text">

  <label>Valor Líquido:</label>
  <input type="text">

  <button type="submit">Enviar</button>
</form>
    
26.09.2017 / 14:06