Skip to content

Call JavaScript function on enter keypress in the textbox | Example code

  • by

You can execute a function by pressing the enter key in a field using the key event in JavaScript. If the user presses the button use the keydown to get know its enter button or not. If it enters the key then call the JavaScript function.

Call javascript function on “Enter” keypress event in textbox example

HTML example code: checks whether the pressed key is “Enter”, if pressed then call function.

Or check event.keyCode == 13 to determine the ‘enter’ keypress.

<!DOCTYPE html>
<html>
<body>
  <input type="text" name="" id="input1">

  <script>
   var input = document.getElementById("input1");
   input.addEventListener("keydown", function (e) {
    if (e.key === "Enter") {  
      validate(e);
    }
  });

   function validate(e) {
    var text = e.target.value;
    alert(text);
  }
</script>
</body>
</html>

Output:

Call JavaScript function on enter keypress in the textbox

Do comment if you have any doubts or suggestions on this JS function call code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *