Coder Perfect

Activate a button In a text box, use JavaScript to press the Enter key.


I have one button and one text input (see below). When the Enter key is hit inside the text box, how can I use JavaScript to trigger the button’s click event?

I can’t just make the button a submit button because there is already a different submit button on my current page. I also want the Enter key to only hit this exact button if it is pressed from within this single text field.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

Asked by kdenney

Solution #1

The following would work with jQuery:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {

Alternatively, the following would work in simple JavaScript:

    .addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {

Answered by Steve Paulo

Solution #2

Then just put it in the code!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"

Answered by Sergey Ilinsky

Solution #3

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

function searchKeyPress(e)
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
        return false;
    return true;

Answered by kdenney

Solution #4

Make the button a submit element to automate the process.

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"

To make this work, you’ll need a form> element that contains the input fields (thanks Sergey Ilinsky).

It’s not a smart idea to change typical behavior; the Enter key should always activate the form’s submit button.

Answered by albertein

Solution #5

Because no one has yet used addEventListener, I’ve created my own version. Given the following elements:

<input type = "text" id = "txt" />
<input type = "button" id = "go" />

I’d go with the following:

var go = document.getElementById("go");
var txt = document.getElementById("txt");

txt.addEventListener("keypress", function(event) {
    if (event.keyCode == 13);

This allows you to change the event type and action independently while maintaining a clean HTML.

Answered by icedwater

Post is based on