I missed that you were using keydown. To prevent form submission, I'd use a submit handler instead, in this case working with your keydown handler and probably a blur handler as well (to reset the flag):
var cancelFlag = false;
$('#TextBox1')
.keydown(function(e) {
cancelFlag = e.keyCode == 13;
})
.blur(function() {
cancelFlag = false;
});
$('#theform').submit(function() {
if (cancelFlag) {
alert("Hello!");
}
return cancelFlag;
});
(Or you can call e.preventDefault(); instead of returning false, 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 alert asynchronous:
$("#TextBox1").keydown(function(e)
{
if(e.keyCode == 13)
{
setTimeout(function()
{
alert("Hello");
}, 10);
return false;
}
});
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...