Jquery prevent ONLY submit on enter

2019-09-18 03:17发布

Why this code works with the alert line commented, but dont work when not commented?

I want block the form submit, but allow other functions on enter (example, do $.get() in other page). Sorry for my bad english.

$(document).ready(function() {
    $('#txtPesquisaServidor').keydown(function(event){
        if(event.keyCode == 13) {
            //alert('enter!');
            event.preventDefault();
            return false;
        }
    });
});

I'm using Jquery 1.6.2.

EDIT: Done! The problem was the alert https://jsfiddle.net/o0mkjnwk/1/

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-18 03:32

Instead of using the .keydown() method, try using .on('keypress', function...

See the following fiddle for a working example: http://jsfiddle.net/p1agoka1/

EDIT: I see you're using jQuery 1.6.2. The .on() event handler requires at least 1.7.0. Is there any reason why you're using such an old version?

If you have some other older code that does not work with a newer version of jQuery, you could try to implement jQuery Migrate which re-enables some older features of jQuery not present in up-to-date versions. https://github.com/jquery/jquery-migrate/

查看更多
登录 后发表回答