Trigger event when the user starts typing in the search field [closed]

3

In the site there is a search field where the user types the product and performs the search.

I would like to trigger a JavaScript event the moment the user begins typing the text into the search field.

Is there any way to do this?

    
asked by anonymous 21.11.2018 / 15:10

2 answers

2

You can do it in two ways. The first is to use the onkeyup event in one tag and the other is to use the keyup() function of JQuery.

JS

function busca(){
    alert("Funcionou");
}
<input type="text" onkeyup="busca()">

JQuery

$("#campo").keyup(function() {
  alert("Funcionou");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="campo">

You can read more about them:

21.11.2018 / 16:27
1

If you need to use pure javascript you can put the onkeyup event in the search input, assigning a javascript function, and in that function do the search action:

function buscar(){
  //Ação de busca
  alert('Buscando...');
}
<input type="text" onkeyup="buscar()">

If you are using JQuery, you can use the event keyup , every time the user types something to trigger an event:

$("#campo_busca").keyup(function() {
  //Ação de busca
  alert('Buscando...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="campo_busca">

There are also events keydown and keypress , however for your case I consider keyup better. You can see the difference here .

Now you only need to adapt to your code.

    
21.11.2018 / 16:15