Problem with onkeyup input

Asked

Viewed 379 times

0

I made a small Javascript function to make a dynamic search in the database without giving refresh and it’s working, but I think there’s a problem with onkeyup. When inserting text into field input and then delete that text, the div#resultado shows all fields registered in the database (which will not be legal). There is another method to remove this bug empty-field?

var req;

// FUNÇÃO PARA BUSCA LOJA
function buscarLojas(valor) {

  // Verificando Browser
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Arquivo PHP juntamente com o valor digitado no campo (método GET)
  var url = "busca.php?valor=" + valor;

  // Chamada do método open para processar a requisição
  req.open("Get", url, true);

  // Quando o objeto recebe o retorno, chamamos a seguinte função;
  req.onreadystatechange = function() {

    // Exibe a mensagem "Buscando lojas..." enquanto carrega
    if (req.readyState == 1) {
      document.getElementById('resultado').innerHTML = 'Buscando lojas...';
    }

    // Verifica se o Ajax realizou todas as operações corretamente
    if (req.readyState == 4 && req.status == 200) {

      // Resposta retornada pelo busca.php
      var resposta = req.responseText;

      // Abaixo colocamos a(s) resposta(s) na div resultado

      document.getElementById('resultado').innerHTML = resposta;

    }
  }
  req.send(null);
}

HTML code:

<div class="search-box">
  <input type="text" name="busca" id="busca" placeholder="Buscar lojas" onkeyup="buscarLojas(this.value)">
  <span></span>

  <div id="resultado"></div>
</div>

3 answers

1

Do a test for the amount of characters the field has before ordering the data, only when it has at least 1 character written:

// FUNÇÃO PARA BUSCA LOJA
function buscarLojas(valor) {
     if(valor.length == 0){
           return false;
     }
...

You can even do it only when it has 2 or 3 characters so that there are not so many results, if that’s the case.

0

onkeyup calls the function when ANY keyboard button is pressed, both the Backspace as to the tab, that is if you delete it will fetch the written result, as the written value is ""(empty string) if you are using a LIKE it will fetch all the bank results, IE, the solution could be on your server php, thus, before bringing the search results try to validate if there is value in the search variable.

0


I was able to follow the hint to put a condition, but it didn’t work with Return false, I was able to pass null to the div#resultado. For those with the same problem, follow the code:

else{
                document.getElementById('resultado').innerHTML = null;
            }

Browser other questions tagged

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