jQuery function that closes the search field by clicking on Esc

Asked

Viewed 213 times

1

On the site where I am developing, there is a field of research that only shows the input when you click on the button.

Now I want to close the input when you click the key Esc (when the focus is in the field). I made a function in jQuery, but it is not working:

FUNCTION:

$('#campo-pesquisa').keypress(function(e) {
    if(e.keyCode === 27) $('#fechar-campo').click();
});

HTML CODE

<div class="form-pesquisa">
                    <form class="input-group" id="campo-pesquisa" action="{{ url }}busca">
                        <input type="text" class="form-control border-right-0" id="input-pesquisa" name="q"
                               aria-label="Campo de busca" placeholder="O que deseja procurar?">
                        <div class="input-group-append">
                            <span class="input-group-text" id="search">
                                <button type="submit">
                                    <span class="ocultaVisualmente">Buscar</span>
                                    <i class="fas fa-search"></i>
                                </button>
                            </span>
                            <span class="input-group-text" id="close-pesquisa">
                                <button type="reset" id="fechar-campo">
                                    <span class="ocultaVisualmente">Fechar Campo de Pesquisa</span>
                                    <i class="fas fa-times"></i>
                                </button>
                            </span>
                        </div>
                    </form>
                </div>
  • And the code that deals with click in #fechar-campo?

1 answer

1


The keypress only detects keys with printable characters (letters, numbers, space etc).

MDN documentation:

inserir a descrição da imagem aqui

Use keydown which detects all keys, then the key ESC will be detected:

$('#campo-pesquisa').keydown(function(e) {
    if(e.keyCode === 27) $('#fechar-campo').click();
});

Browser other questions tagged

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