简体   繁体   中英

keypress event is not fired when we press enter key

I am facing a problem regarding to the keypress event. When I press the enter key then keypress event is not fired but it is working fine with the other keys.

Here is my code:

$(document).ready(function () {
        alert('hi');
        $("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keypress(function (e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            alert(code);
            if (code == 13) { //Enter keycode
                //Do something
            }
        });
    });

You should use keyup event for this

$(document).ready(function() {
    $("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keyup(function(e) {
        if (e.which == 13) {
            //Enter keycode //Do something 
        }
    });
});

Use just e.which as its normalized across keys:

$(document).ready(function () {
        alert('hi');
        $("#ctl00_popupPageBody_txtFirstName,#ctl00_popupPageBody_txtLastName").keypress(function (e) {
            var code = e.which; 
            alert(code);
            if (code === 13) { //Enter keycode
                e.preventDefault();
                //your code goes here
            }
        });
    });

Note: in my case I bind do.keydown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM