【问题标题】:Restrict the Enter key press [duplicate]限制按 Enter 键 [重复]
【发布时间】:2012-11-13 15:47:58
【问题描述】:

可能重复:
Prevent form submission with enter key

在我的项目中,我正在尝试禁用 Enter 键并提供我自己的 Enter 键功能。(我还没有这样做

以下功能正在运行,但每当我在 TextBox 字段中按 Enter 键时,内容将添加到 div(根据需要)以及 TextBox 字段中,请输入关键功能正在发生(我不想要)。如何停止输入键功能在TextBox 字段上运行?为了清楚理解,请参阅下面代码中的我的 cmets。

.aspx 文件工作

<asp:TextBox ID="msg" BackColor="Transparent" runat="server" BorderStyle="None"
                        TextMode="MultiLine" />

jQuery工作

$('#msg').keypress(function (e) {
            if (e.which == 13) {

                //Shows the TextBox text in a Div, which I want to.
                chat.server.send($('#msg').val());  //also going one step down in TextBox field which I dont want to.

                $('#msg').val(''); //Clearing the Text in TextBox field

                //what should I add here to make the Enter Key work only for the DIV?
            }
        });

source

【问题讨论】:

  • 是的,看看你问过的重复问题,就像其他一百万人一样......
  • @Ian close 在得到一个好的答案后会有什么好处? :)
  • 您应该在发布问题之前仔细检查。
  • @AbijeetPatro 在问这里之前我搜索了很多。我不知道duplicate question 的关键字是什么。顺便说一句,堆栈溢出是为了进行问答。我们应该在我们的帖子中展示我所做的研究,你可以清楚地看到。

标签: javascript jquery asp.net


【解决方案1】:

试试e.preventDefault() 像这样

$('#msg').keypress(function (e) {
            if (e.which == 13) {
                e.preventDefault();
                //Shows the TextBox text in a Div, which I want to.
                chat.server.send($('#msg').val());  //also going one step down in TextBox field which I dont want to.

                $('#msg').val(''); //Clearing the Text in TextBox field

                //what should I add here to make the Enter Key work only for the DIV?
            }
        });

【讨论】:

    【解决方案2】:

    还可以尝试使用 C# 在 C# 中进行验证。只需编写下面的函数并调用提供参数的函数(如下所述)

    public void disable_TextBox_Enter(Control parent)
        {
            foreach (Control c in parent.Controls)
            {
                if ((c.Controls.Count > 0))
                {
                    disable_TextBox_Enter(c);
                }
                else
                {
                    if (c is TextBox)
                    {
                        ((TextBox)(c)).Attributes.Add("onkeydown", "return (event.keyCode!=13);");
    
                    }
                    if (c is GridView)
                    {
    
                        ((GridView)(c)).Attributes.Add("onkeydown", "return (event.keyCode!=13);");
    
                    }
    
                }
            }
        }
    

    你可以像这样调用函数:

    disable_TextBox_Enter(this);
    

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 2014-09-20
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 2012-10-21
      • 2016-11-13
      • 1970-01-01
      相关资源
      最近更新 更多