Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Start searching after clicking on search button

I have to start the search when search button is clicked. So I have added click event on search button. When I click on button startSearch function is called. And that function adds an event on input element. Now let's say I have typed TEXT in form and I clicked the search button, nothing happens. But If I later type something else search is activated. How to do this properly?

document.querySelector('.searchBtn').addEventListener('click', 
startSearch); //button

const inputSearch = document.querySelector('.inputSearch');

function startSearch(){
    inputSearch.addEventListener('keyup', searchFunction);
}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You will have to set the event listeners as soon as the HTML document is loaded (See DOMContentLoaded event). You are registering the event handler once the search button is clicked, but you need to start the search when it is clicked so you need to set the event handler before that. Then activate the search function in the event handler. An event can only be registered if an event handler is set before the event occurs.

The following implementation will start a search once the value in the input field changes or the search button is clicked.

function searchFunction(searchTerm) {
  console.log(`Searching for ${searchTerm}...`)
}

window.addEventListener("DOMContentLoaded", (e) => {
  const btn = document.querySelector(".searchBtn");
  const input = document.querySelector(".inputSearch");

  btn.addEventListener("click", (e) => {
    // get value of input field first
    searchFunction(input.value);
  });
  input.addEventListener("keyup", (e) => searchFunction(e.target.value));
});
<input class="inputSearch" />
<button class="searchBtn">Search</button>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda