Trying to 'submit' my form when hitting enter fails

我们两清 提交于 2019-12-13 08:41:20

问题


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/



来源:https://stackoverflow.com/questions/8071285/trying-to-submit-my-form-when-hitting-enter-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!