Thursday, 5 September 2013

Prevent postback on Enter in a asp.net inputfield

Prevent postback on Enter in a asp.net inputfield

I have a problem with the key Enter in javascript and asp.net
I have a control like this with a textchanged event which does a find but
I want to control it when the user does enter
<asp:TextBox ID="TextBox1" runat="server" onkeyup="EnterEvent(event)"
AutoPostBack="true" OnTextChanged="TextBox1_TextChanged" />
That's why I created this javascript function which works very well.
Because it avoids the Enter postback at any character input
function EnterEvent(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == 13) {
return true;
}
else {
return false
}
}
And then I wanted to control when the TextBox has content, so I changed
the js like this.
function EnterEvent(e, ctrl) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == 13) {
return ctrl.value.length > 2;
}
else {
return false
}
}
The control
<asp:TextBox ID="TextBox1" runat="server" onkeyup="EnterEvent(event,
this)" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged" />
But nothing happens. Anytime that I do Enter, the page postback.
I also added this in the code behind on the load page
TextBox1.Attributes.Add("onkeypress", "EnterEvent(event,
this);");
TextBox1.Attributes.Add("onkeyup", "EnterEvent(event, this);");
TextBox1.Attributes.Add("onkeydown", "EnterEvent(event, this);");
My page is still doing postback at Enter key. The idea is to stop the
Enter postback if at least has 3 characters. Any idea or another approach?

No comments:

Post a Comment