Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!