Home >Web Front-end >JS Tutorial >How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?

How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 08:57:11908browse

How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?

Trigger Button Click from Text Box Enter Key with JavaScript

To trigger a button's click event when the Enter key is pressed inside a specific text box, leverage the following jQuery code:

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

Here's how it works:

  • $("#id_of_textbox"): Selects the text box element by its ID.
  • .keyup(function(event)): Registers a keyup event listener on the text box.
  • event.keyCode === 13: Checks if the key code pressed is 13, which corresponds to the Enter key.
  • $("#id_of_button").click(): Triggers the click event on the button element with the specified ID.

For example, consider the following HTML:

<input type="text">

To trigger the "Search" button click when Enter is pressed in the "txtSearch" text box, use this jQuery code:

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

The above is the detailed content of How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn