HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
enterkeywithboxbuttontextthejavascripttriggerclick

Problem

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.

Solution

In jQuery, the following would work:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});




$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});

$("#myButton").click(function() {
alert("Button code executed.");
});



Username:

Password: 

Submit




Or in plain JavaScript, the following would work:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});




document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});

function buttonCode()
{
alert("Button code executed.");
}



Username:

Password: 

Submit

Code Snippets

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});
document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});

Context

Stack Overflow Q#155188, score: 1560

Revisions (0)

No revisions yet.