Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 输入时jquery禁用表单提交(jquery disable form submit on enter)

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

(我的页面中有以下javascript似乎不起作用。)

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

I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit.

(我想禁止在输入时提交表单,或者更好的是,调用我的ajax表单提交。)

Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

(这两种解决方案都是可以接受的,但我上面提到的代码并不能阻止表单提交。)

  ask by Adam Levitt translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If keyCode is not caught, catch which :

(如果keyCode没有被捕获,赶上which :)

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

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

(编辑:错过了,最好使用keyup而不是keypress)

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.

(编辑2:与一些较新版本的Firefox一样,表单提交没有被阻止,将keypress事件添加到表单也更安全。)

Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id.

(它也不起作用(不再?)只是将事件绑定到表单“name”但仅限于表单id。)

Therefore I made this more obvious by changing the code example appropriately.

(因此,我通过适当地更改代码示例使这一点变得更加明显。)

EDIT 3: Changed bind() to on()

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...