What is the usage of onsearch event in JavaScript?

The onsearch event triggers when a user interacts with a search input field by pressing ENTER or clicking the "x" (clear) button. This event only works with <input type="search"> elements and provides a convenient way to handle search operations.

Syntax

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

// Or using addEventListener
element.addEventListener("search", myFunction);

Example

Here's how to implement the onsearch event to capture user search input:

<!DOCTYPE html>
<html>
<head>
    <title>OnSearch Event Example</title>
</head>
<body>
    <p>Write what you want to search below and press "ENTER" or click the "x" to clear:</p>
    
    <input type="search" id="searchInput" onsearch="handleSearch()" placeholder="Enter search term...">
    <p id="result"></p>
    
    <script>
        function handleSearch() {
            var input = document.getElementById("searchInput");
            var result = document.getElementById("result");
            
            if (input.value.trim() === "") {
                result.innerHTML = "Search cleared!";
            } else {
                result.innerHTML = "You searched for: " + input.value;
            }
        }
    </script>
</body>
</html>

Using addEventListener Method

You can also attach the event listener programmatically:

<!DOCTYPE html>
<html>
<body>
    <input type="search" id="mySearch" placeholder="Search here...">
    <div id="output"></div>
    
    <script>
        var searchBox = document.getElementById("mySearch");
        
        searchBox.addEventListener("search", function() {
            var output = document.getElementById("output");
            if (this.value === "") {
                output.innerHTML = "Search field was cleared";
            } else {
                output.innerHTML = "Searching for: " + this.value;
            }
        });
    </script>
</body>
</html>

Browser Compatibility

Browser Support
Chrome Yes
Safari Yes
Firefox No
Internet Explorer No
Opera No

Key Points

  • Only works with <input type="search"> elements
  • Triggers when user presses ENTER or clicks the clear (x) button
  • Limited browser support - mainly WebKit browsers (Chrome, Safari)
  • Use input or keyup events for better cross-browser compatibility

Conclusion

The onsearch event provides a convenient way to handle search input interactions, but its limited browser support means you should consider alternative events like input or keyup for broader compatibility.

Updated on: 2026-03-15T23:18:59+05:30

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements