限制Enter键按

可能重复:
使用回车键阻止表单提交

在我的项目中,我试图禁用Enter键并给出我自己的回车键function。( 我没做过

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

.aspx文件工作

  

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? } }); 

资源

像这样尝试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? } }); 

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

 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);