停止输入/回车键提交表格 [英] Stop Enter/Return key submitting a form

查看:160
本文介绍了停止输入/回车键提交表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表格。该表包含一些表单字段,但表格外部还有表单字段(但仍在表单中)。



我知道Enter和Return传统上用于通过键盘提交表单,但我想停止表中字段的这种行为。例如,如果我将表中的一个字段聚焦并按Enter / Return,则不会发生任何事情。如果我把一个字段集中在表格之外(但仍然在表单中),然后让它正常提交。



我有一个针对此表的jQuery插件。简化,这是我已经尝试了这么多:

$ $ $ $ $ $ $ $ base.on('keydown',function(e){
if(e.keyCode == 13){
e.stopPropagation();
return false;
}
});

其中 base 是表jQuery对象。这是在我的插件的 init 方法中。然而,按Enter键仍然会提交表格。



我在哪里出错?

编辑: 一些简化的HTML:

 < form method =action => 
< input type =text/><! - 这仍然会在Enter上提交 - >
< table>
< tbody>
< tr>
< td>
< input type =text/><! - 这不应该在Enter上提交 - >
< / td>
< / tr>
< / tbody>
< / table>
< / form>


解决方案

  base。 keypress(function(e){
var code = e.keyCode || e.which;
if(code == 13)
return false;
});

或仅用于输入:

<$ p $如果(代码==)($)代码== 13)
返回false;
});


I have a table within a form. The table contains some form fields, but there are form fields outside of the table (but still within the form) too.

I know that Enter and Return are traditionally used to submit a form via the keyboard, but I want to stop this behaviour for fields within the table. For example, if I focus a field within the table and hit Enter/Return, nothing happens. If I focus a field outside of the table (but still within the form) then for it to submit as normal.

I have a jQuery plugin that targets this table. Simplified, this is what I've tried this far:

base.on('keydown', function(e) {
    if (e.keyCode == 13) {
        e.stopPropagation();
        return false;
    }
});

Where base is the table jQuery object. This is within my plugin's init method. However, hitting Enter still submits the form.

Where am I going wrong?

EDIT: Some simplified HTML:

<form method="" action="">
  <input type="text" /><!--this should still submit on Enter-->
  <table>
    <tbody>
      <tr>
        <td>
          <input type="text" /><!--this should NOT submit on Enter-->
        </td>
      </tr>
    </tbody>
  </table>
</form>

解决方案

base.keypress(function(e) {
    var code = e.keyCode || e.which;
    if(code == 13)
        return false;
});

or for only inputs:

$(':input', base).keypress(function(e) {
    var code = e.keyCode || e.which;
    if(code == 13)
        return false;
});

这篇关于停止输入/回车键提交表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆