In ASP.NET, I am preventing default postback action when user presses enter while textbox control has focus. See the following piece of code
$("#TextBox1").keydown(function(e)
{
if(e.keyCode == 13)
{
//alert("Hello");
return false;
}
});
This code works fine. But if I uncomment the alert function call then page post does not stop.
My question is why alert call is creating a problem?
I missed that you were using
keydown. To prevent form submission, I’d use asubmithandler instead, in this case working with yourkeydownhandler and probably ablurhandler as well (to reset the flag):(Or you can call
e.preventDefault();instead of returningfalse, either works.) You’ll need to do testing to ensure the flag gets cleared in every situation you want it to be cleared in.Alternately, make the
alertasynchronous:That lets the event stack unwind before putting up the alert. But I’m not at all sure you can reliably (cross-browser and OS) prevent a form submission by cancelling the default action of a
keydown. You said it was working, and if it works in your target browsers, great, but…