Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript在文本框中的Enter键上触发按钮单击(Trigger a button click with JavaScript on the Enter key in a text box)

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?

(当在文本框中按下Enter键时,如何使用JavaScript 触发按钮的click事件 ?)

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.

(而且,如果从一个文本框中按下该按钮,我希望按Enter键即可单击该特定按钮,没有别的。)

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
  ask by kdenney translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In jQuery, the following would work:

(在jQuery中,以下将起作用:)

$("#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."); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton">Submit</button> 

Or in plain JavaScript, the following would work:

(或在普通的JavaScript中,以下方法将起作用:)

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."); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password:&nbsp;<input id="pw" type="password"><br> <button id="myButton" onclick="buttonCode()">Submit</button> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...