最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

prototypejs - Submit form when enter key pressed using Prototype javascript - Stack Overflow

programmeradmin1浏览0评论

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

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

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

Thanks!

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

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

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

Thanks!

Share Improve this question edited Dec 28, 2011 at 11:45 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Sep 9, 2010 at 9:44 Brian ArmstrongBrian Armstrong 19.9k17 gold badges118 silver badges144 bronze badges 1
  • I can't offer any Prototype-specific advice, but have you considered adding a submit button and then hiding it with Prototype/JS? It's not the answer you want, but it degrades nicely. – David Thomas Commented Sep 9, 2010 at 9:51
Add a comment  | 

3 Answers 3

Reset to default 10

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;   
    }
}

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);
    }
});

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();
                }
            });
        });
    });
});
发布评论

评论列表(0)

  1. 暂无评论