HTML onsearch Event Attribute

Description

The onsearch HTML event attribute is used to specify a JavaScript function that will be executed when the user presses the "Enter" key or clicks the "x" button in a search input field.

This event attribute can be used to trigger a variety of actions, such as submitting the search query to a server, performing a local search on the client side, or displaying a list of suggestions.

The following is an example of how to use the onsearch event attribute:

<input type="search" onsearch="myFunction()">

In the above example, the myFunction() function will be executed when the user presses the "Enter" key or clicks the "x" button in the search input field.

Here is an example of a simple myFunction() function:

function myFunction() {
  // Get the search query from the input field.
  var searchQuery = document.querySelector('input[type="search"]').value;

  // Submit the search query to a server.
  // ...

  // Perform a local search on the client side.
  // ...

  // Display a list of suggestions.
  // ...
}

Syntax

<element onsearch="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onsearch event</title>
</head>
<body>
<p>Type something and hit enter:</p>
<input type="search" id="testInput" onsearch="testFunction()">
<p id="info"> </p>
<script>
function testFunction() {
var z = document.getElementById("testInput").value;
document.getElementById("info").innerHTML = "You are looking for: " + z;
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onsearch Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023