Trying to 'submit' my form when hitting en

2019-08-30 13:45发布

问题:

I have a form with a hidden submit button.

When I try to submit the form using the enter key it fails (alert doesn't display).

I use the following JS:

$(function() {
    $('div.quick-login form').submit(function() {
        alert('test');

        return false;
    });
});

http://jsfiddle.net/MsFY6/

Any ideas as to why my code doesn't work?

UPDATE

Browser I tested it with is Chrome.

回答1:

What I always do is put in a .keypress() handler which checks the keycode.

$("#inputbox").keypress(function(e) {
  if(e.keyCode == 13) {
    alert('test');
  }
});


回答2:

Works for me in FireFox 8.0 and IE 8. What browser are you using? They do have this disclaimer in the documentation for submit:

Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.

Sounds like you shouldn't be counting on the Enter key.



回答3:

I can reproduce the error in Safari/Chrome. The reason is because the submit button is display: none;-ed. If you unhide it, it works, you can also do visibilty: hidden; and have it work.

An option may be to bind to a keypress as well - the return key, keyCode is 13.



回答4:

I've modified your example:

With keycode: http://jsfiddle.net/MsFY6/7/

With visibilty hidden: http://jsfiddle.net/MsFY6/8/