Showing data when typing

Asked

Viewed 178 times

3

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

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

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

Obs. the intention is only shows 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>

1 answer

4


You can do it using the keyup in the input thus:

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>

  • Excuse the ignorance, but need to import some library to use this function? could not perform the function here.. kk

  • @Smokerohden doesn’t need any library, it’s all native Javascript. If you can’t get it to work create a jsFiddle with an example I help. But as a test you can put Javascript after HTML in the page.

  • You could even create the variables of inputs with Destructuring

  • Got it. I put it in the end it worked!

  • Thanks @Sergio really worth it

  • @Isac yes, it would be cleaner const [valor, ir, liquido] = [...document.querySelectorAll('form input')];

Show 1 more comment

Browser other questions tagged

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