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.


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

<!DOCTYPE html>
      <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>
         function display() {
         var a = document.getElementById("inputID");
         document.getElementById("test").innerHTML = "Searched for - " + a.value;

Updated on: 03-Mar-2020


Kickstart Your Career

Get certified by completing the course

Get Started