Trigger Button Click on Keyboard Enter with JavaScript
To trigger a button click on keyboard "enter" with JavaScript, the code is as follows −
Example
<!DOCTYPE html> <html> <head> <h1>Trigger Button Click on Enter Example</h1> <input id="inputField" value="Some text.." /> <button id="alertBtn" onclick="alert('Button has been clicked')"> Button </button> <h2> Press the "Enter" key inside the above input field to trigger the button. </h2> <script> var inputText = document.getElementById("inputField"); inputText.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("alertBtn").click(); } }); </script> </body> </html>
Output
The above code will produce the following output −
On typing something in the field and then pressing enter −
Advertisements