Execute a script when the user writes something in a search field in HTML?


Use the onsearch attribute in HTML to execute a script when the user writes in a search field and press ENTER or x.

Example

You can try to run the following code to implement the onsearch attribute −

<!DOCTYPE html>
<html>
   <body>
      <p>Search something and press ENTER.</p>
      <input type = "search" id="inputID" onsearch = "display()">
      <p><strong>Note:</strong> It won' work in Internet Explorer and Firefox.</p>
      <p id="test"></p>
      <script>
         function display() {
         var a = document.getElementById("inputID");
         document.getElementById("test").innerHTML = "Searched for - " + a.value;
         }
      </script>
   </body>
</html>

Updated on: 03-Mar-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements