Enter key press event in JavaScript

2018-12-31 08:41发布

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call a javascript function (User defined), but when I press it, the form is submitted.

How do I prevent the form from being submitted when the enter key is pressed?

14条回答
低头抚发
2楼-- · 2018-12-31 09:35

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

查看更多
有味是清欢
3楼-- · 2018-12-31 09:37

If you're using jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});
查看更多
登录 后发表回答