Function going into loop for no reason

Asked

Viewed 72 times

1

I have a script to increment a value in a input multiplication when + or - is pressed. It is working as expected as long as it is not phocus in the input multiplication.

At each phocus in the input the script gets into loop when triggered (when keyboard shortcuts are pressed). That is, if the value is "1" and press + the value becomes "2" as expected, but if the phocus in the input multiplication and presses + the value becomes "4" and not "3".

Using the console.logI realized that you enter a loop, from "2" to "3" and repeating from "3" to "4".

//Adiciona ou Subtrai multiplicador com teclado
$("#valorBuscaProduto").focusin(function() {
  $(this).keydown(function(e) {

    //Caso '+' seja apertado
    if (e.keyCode == 187 || e.wich == 187) {
      e.preventDefault();

      var multiplicador = $("#inputMultiplicador").val().replace(",", ".");

      multiplicador = parseFloat(multiplicador);
      console.log(multiplicador);

      multiplicador = multiplicador + 1;
      console.log(multiplicador);

      $("#inputMultiplicador").val(multiplicador);

    }

    //Caso '-' seja apertado
    if (e.keyCode == 189 || e.wich == 189) {
      e.preventDefault();

      var multiplicador = $("#inputMultiplicador").val().replace(",", ".");

      multiplicador = parseFloat(multiplicador);
      console.log(multiplicador);

      if (multiplicador > 0) {
        multiplicador = multiplicador - 1;
        console.log(multiplicador);
      }

      $("#inputMultiplicador").val(multiplicador);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form id="buscarProduto" class="barraPesquisa" method="post">
  <div id="multiplicador">
    <input id="inputMultiplicador" name="multiplicador" value="1">
  </div>
  <input type="search" id="valorBuscaProduto" name="valorBuscaProduto" placeholder="Buscar Produto">
  <input type="submit" name="submitBuscarProduto" value="Buscar">
</form>

  • I tried to reproduce the problem that commented and could not. I could check if your code is complete and try to elaborate a [mcve]?

1 answer

0


Take off the $(this).keydown(...) out of the ("#valorBuscaProduto").focusin(), delete the latter and change the this for "#valorBuscaProduto", getting only with:

$("#valorBuscaProduto").keydown(...)

That’s because you are, the way you are now, every time you focus on #valorBuscaProduto, applying a new event handler keydown in this HTML element.

  • 1

    Actually, I was concerned to limit the action to the #valorBuscaProduto that I’ve forgotten that the keydown would already be doing that.

Browser other questions tagged

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