javascript 使用原型javascript按下输入键时提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3675442/
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-10-25 01:54:00  来源:igfitidea点击:

Submit form when enter key pressed using Prototype javascript

javascriptprototypejs

提问by Brian Armstrong

I've seen some other questions around this, but none for Prototype.

我已经看到了一些关于此的其他问题,但没有针对 Prototype。

I have a form without a submit button (uses a styled link that calls some javascript).

我有一个没有提交按钮的表单(使用调用一些 javascript 的样式链接)。

What's the best way to detect a enter keypress in all the input fields and submit the form?

在所有输入字段中检测输入按键并提交表单的最佳方法是什么?

Thanks!

谢谢!

回答by robjmills

This is an example of the kind of thing you could use:

这是您可以使用的类型的示例:

$('input').observe('keypress', keypressHandler);

function keypressHandler (event){
    var key = event.which || event.keyCode;
    switch (key) {
        default:
        break;
        case Event.KEY_RETURN:
            $('yourform').submit();
        break;   
    }
}

回答by bradypus

It is the same as above but does not need to set a function:

和上面一样但是不需要设置函数:

$('input').observe('keypress', function(event){
    if ( event.keyCode == Event.KEY_RETURN  || event.which == Event.KEY_RETURN ) {
        // enter here your code
        Event.stop(event);
    }
});

回答by Globule Bleu

With Prototype:

带原型:

document.observe("dom:loaded", function() {
    $$('form').each(function(f) {
        $(f).select("input").each(function(e) {
            e.observe('keypress', function(event) {
                if ( event.keyCode == Event.KEY_RETURN  || event.which == Event.KEY_RETURN ) {
                    this.form.submit();
                }
            });
        });
    });
});