Jquery prevent ONLY submit on enter

蓝咒 提交于 2020-01-17 08:26:29

问题


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:


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/



来源:https://stackoverflow.com/questions/32789605/jquery-prevent-only-submit-on-enter

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