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

243
Views
Can I add event to the button on click of input type=search?

Is there any event available for clicking clear button only appears on html5 search input element?

Here is my attempt. But if i use "search", the event is also triggered by pressing enter.

i.e. if i press enter, console prints out search clear

  mySearchBar.addEventListener("keydown", (e) => {
    if (e.keyCode === ENTER_KEY_CODE) {
       console.log("search");
       //Display search results
    }
  });

  mySearchBar.addEventListener("search", () => {
    console.log("clear");
    // Click the cross button of input type=search to Clear the search results and display all
  });
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use eventListener 'input' to check if input is empty each time something append to input, then if no value that mean the search input was cleared.

EDIT: Added value testing in keydown event

mySearchBar = document.getElementById('search');
mySearchBar.addEventListener("keydown", (e) => {
  if (e.key === 'Enter') {
    if (!e.currentTarget.value)
      console.log('cleared');
    else
      console.log("search");
  }
});
mySearchBar.addEventListener('input', (e) => {
  if (!e.currentTarget.value)
    console.log('cleared');
})
<input type=search id=search>

about 4 years ago · Juan Pablo Isaza 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!