The HTML onsearch attribute is an event handler used to specify a script that will run when the user initiates a search action in the input field.
Definition and Usage
➔ This applies to the <input> element when its type attribute is set to "search".
➔ The event is triggered when the user presses the "Enter" key.
➔ The event is also fired when the user clicks the "x" (clear) button and the cursor moves into the search input field for further typing.
➔ This allows JavaScript code to be executed to handle search queries without submitting an HTML form.
Syntax
//In HTML
<input type="search" id="sample" onsearch="myFunction()">
//In javascript
document.getElementById("sample").onsearch=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("search", myFunction);
//OR
document.getElementById("sample").addEventListener("scroll", (event) => {
myFunction();
});
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onsearch Attribute Example</title>
<meta charset="utf-8" />
<style>
#sample {
background-color: skyblue;
}
</style>
</head>
<body>
<h2>HTML onsearch Attribute Example</h2>
<p>Type something in the search field and press enter key to trigger event.</p>
<p id="mypara">You search for text:</p>
<input type="search" id="sample" onsearch="myFunction()">
<script>
function myFunction() {
document.querySelector("#mypara").innerHTML = "You search for text: "+document.getElementById("sample").value;
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.