I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins
Since no one has used addEventListener
yet, here is my version. Given the elements:
I would use the following:
var go = document.getElementById("go");
var txt = document.getElementById("txt");
txt.addEventListener("keypress", function(event) {
event.preventDefault();
if (event.keyCode == 13)
go.click();
});
This allows you to change the event type and action separately while keeping the HTML clean.
Note that it's probably worthwhile to make sure this is outside of a
because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.
Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a
preventDefault
to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)