Javascript 将回车键聚焦到特定按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12389367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:52:00  来源:igfitidea点击:

Focus an enter key to a specific button

javascriptjqueryhtml

提问by Sboniso Marcus Nzimande

I am currently facing a problem.

我目前面临一个问题。

I need have a form to be fill by a user ie:

我需要一个用户填写的表格,即:

field1: <input type='text' name='field1'>
field1: <input type='text' name='field1'>
<input type='button' value='Save' name='Save'>

So now I need the way to focus on the 'Save' button when a user has filled the last text box in a form, so that even when the user clicks on the 'Enter' button the save event get run.

所以现在我需要一种在用户填写表单中的最后一个文本框时关注“保存”按钮的方法,这样即使用户点击“输入”按钮,保存事件也会运行。

This usually happens automatically but the problem is I have many buttons in my page, now when a user click on save another click event(that I don't want) gets fired up.

这通常会自动发生,但问题是我的页面中有很多按钮,现在当用户点击保存另一个点击事件(我不想要的)被触发时。

So my question is how do I control what should happen when the ENTER button is clicked, or should I disable this event?

所以我的问题是如何控制单击 ENTER 按钮时应该发生的情况,还是应该禁用此事件?

回答by Vivek S

The way to accomplish that is by using javascript, and I'd suggest you using jQuery.

实现这一点的方法是使用 javascript,我建议您使用 jQuery。

$('#mytextfield').change(function(e) {
    $('input[type=submit]').focus();
});

You can also autofocus an element on HTML5 by adding the attribute autofocus="autofocus"

您还可以通过添加属性 autofocus="autofocus" 在 HTML5 上自动聚焦元素

Take a look at the small demo : http://jsfiddle.net/9WmQ5/

看看小演示:http: //jsfiddle.net/9WmQ5/

回答by Santiago Elvira Ramirez

you have to put the button inside the form

你必须把按钮放在表单中

<form>
<input type="submit" value='Save' name='Save'>
</form>

in that way when you press enter the event will be executed remeber type="submit"

这样,当您按下 Enter 时,事件将被执行,请记住 type="submit"

回答by Vytalyi

You can write a function to listen which key is pressed

您可以编写一个函数来监听按下了哪个键

function keyPressListener(e) {
        if (e.keyCode == 13) {
                 // do something
    }
}

and then add onkeypress attribute to your input textbox

然后将 onkeypress 属性添加到您的输入文本框

onkeypress="keyPressListener(event)"

回答by Kumar Albert

Without using JQuery,

不使用JQuery,

document.getElementById('idName').focus();

Above line is used focus your element

上面的行用于聚焦您的元素

回答by Murali Murugesan

This could help to solve

这可以帮助解决

field1: <input type='text' name='field1'>
field1: <input type='text' name='field1' id='last-name'>
<input type='button' value='Save' id='save-btn' name='Save'>


<script>

$(document).ready(function(){
$('#last-name').blur(function(){ $('#save-btn').focus(); });

});

</script>