Somewtimes, we want to trigger HTML button click when pressing Enter in a text box with JavaScript
In this article, we’ll look at how to trigger HTML button click when pressing Enter in a text box with JavaScript
How to trigger HTML button click when pressing Enter in a text box with JavaScript?
To trigger HTML button click when pressing Enter in a text box with JavaScript, we call click
on the button.
For instance, we write
document.getElementById("addLinks").onkeypress = (e) => {
if (e.keyCode === 13) {
document.getElementById("linkadd").click();
}
};
to select the text box with document.getElementById("addLinks")
.
Then we set its onkeypress
property to a function that’s called when we press a key when focus on the text box.
In it, we check if enter is pressed with e.keyCode === 13
.
If it’s true
, then we click the button with document.getElementById("linkadd").click();
.
Conclusion
To trigger HTML button click when pressing Enter in a text box with JavaScript, we call click
on the button.