Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda