Home Trigger a button click with JavaScript on the Enter key in a text box
Reply: 0

Trigger a button click with JavaScript on the Enter key in a text box

user7155
1#
user7155 Published in September 19, 2018, 11:08 am

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 inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
share|improve this question
  • 1
    Important note for rookies like me: The key part of this question is if you already have a form on the page so already have a submit button. The jQuery answer is cross browser compatible and a good solution. – Joshua Dance Aug 18 '14 at 17:38
  • 2
    @JoshuaDance, already having a form/submit is not a trouble. A page can have many forms (but not nested), each having their own submit. Every field of each form will trigger only the submit of that form. As stated by this answer. – Frédéric Jan 14 '16 at 11:19

25 Answers 25

active oldest votes
up vote 1295 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.441509 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO