本文介绍了jquery 在输入时禁用表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面中有以下 javascript,但似乎不起作用.

I have the following javascript in my page which does not seem to be working.

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});

我想禁用在输入时提交表单,或者更好的是,调用我的 ajax 表单提交.两种解决方案都可以接受,但我上面包含的代码不会阻止表单提交.

I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

推荐答案

如果 keyCode 没有被捕获,则捕获 which:

If keyCode is not caught, catch which:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) {
    e.preventDefault();
    return false;
  }
});

错过了,最好使用 keyup 而不是 keypress

missed it, it's better to use keyup instead of keypress

编辑 2:在某些较新版本的 Firefox 中,不会阻止表单提交,将按键事件添加到表单中也更安全.它也不起作用(不再?)仅将事件绑定到表单名称",但仅绑定到表单 id.因此,我通过适当更改代码示例使这一点更加明显.

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

编辑 3:将 bind() 更改为 on()

EDIT 3: Changed bind() to on()

这篇关于jquery 在输入时禁用表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:06