Submitting a form on 'Enter' with jQuery?

后端 未结 14 2004
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 14:45

I have a bog-standard login form - an email text field, a password field and a submit button on an AIR project that\'s using HTML/jQuery. When I hit Enter on the form, the

14条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 15:14

    I found out today the keypress event is not fired when hitting the Enter key, so you might want to switch to keydown() or keyup() instead.

    My test script:

            $('.module input').keydown(function (e) {
                var keyCode = e.which;
                console.log("keydown ("+keyCode+")")
                if (keyCode == 13) {
                    console.log("enter");
                    return false;
                }
            });
            $('.module input').keyup(function (e) {
                var keyCode = e.which;
                console.log("keyup ("+keyCode+")")
                if (keyCode == 13) {
                    console.log("enter");
                    return false;
                }
            });
            $('.module input').keypress(function (e) {
                var keyCode = e.which;
                console.log("keypress ("+keyCode+")");
                if (keyCode == 13) {
                    console.log("Enter");
                    return false;
                }
            });
    

    The output in the console when typing "A Enter B" on the keyboard:

    keydown (65)
    keypress (97)
    keyup (65)
    
    keydown (13)
    enter
    keyup (13)
    enter
    
    keydown (66)
    keypress (98)
    keyup (66)
    

    You see in the second sequence the 'keypress' is missing, but keydown and keyup register code '13' as being pressed/released. As per jQuery documentation on the function keypress():

    Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
    

    Tested on IE11 and FF61 on Server 2012 R2

提交回复
热议问题