References

Beginner-friendly references for web development, with live, editable examples.

The HTML onsearch event

Event Updated
Quick answer

The HTML onsearch attribute runs JavaScript when the user submits or clears an <input type="search"> (by pressing Enter or clicking the clear "×"). It is non-standard (a WebKit/Blink feature), so for portable search prefer a debounced oninput handler.

Overview

The onsearch event attribute runs JavaScript when a search input is submitted or cleared (non-standard). In JavaScript the event itself is named search. Drop the on prefix when you call addEventListener.

It is a form-related event, fired by form controls such as <input>, <select> and <textarea> (or the <form> itself) as the user interacts with them and as data is submitted or validated.

You can wire this up with the inline onsearch HTML attribute or with addEventListener, but because the event is non-standard and only implemented in WebKit and Blink, portable code should use a debounced input (or change) listener instead.

Non-standard. onsearch is non-standard and only works on <input type="search"> in some browsers. Use oninput or onchange for reliable behavior.

Syntax

<!-- Non-standard. Prefer a debounced oninput. -->
<input type="search" onsearch="runSearch(this.value)">

Example

Live example
<input type="search" onsearch="this.nextElementSibling.textContent = 'Searched: ' + this.value" placeholder="Type and press Enter" style="padding:8px;"><span></span>

Best practices

  • Prefer element.addEventListener('search', handler) over the inline onsearch attribute; it separates behavior from markup and allows multiple handlers.
  • Use native form validation (required, type, pattern) alongside JavaScript, not instead of it.
  • Re-validate on the server too; client-side events can be bypassed.
  • Give every control a <label> so the interaction is accessible.

Frequently asked questions

What is the onsearch event?
It runs JavaScript when a search input is submitted or cleared (non-standard). In JavaScript the event is named search.
What is the difference between oninput and onchange?
oninput fires on every keystroke as the value changes; onchange fires once the value is committed (often on blur).
Should I rely on form events for validation?
Use them for instant feedback, but always validate again on the server, since client-side checks can be bypassed.
Should I use the onsearch attribute or addEventListener?
Neither is portable. The search event is non-standard and missing in Firefox, so use a debounced input (or change) listener instead.