jquery - JavaScript alert function behaviour -
in asp.net, preventing default postback action when user presses enter while textbox control has focus. see following piece of code
$("#textbox1").keydown(function(e) { if(e.keycode == 13) { //alert("hello"); return false; } });
this code works fine. if uncomment alert function call page post not stop.
my question why alert call creating problem?
i missed using keydown
. prevent form submission, i'd use submit
handler instead, in case working keydown
handler , blur
handler (to reset 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 can call e.preventdefault();
instead of returning false
, either works.) you'll need testing ensure flag gets cleared in every situation want cleared in.
alternately, make alert
asynchronous:
$("#textbox1").keydown(function(e) { if(e.keycode == 13) { settimeout(function() { alert("hello"); }, 10); return false; } });
that lets event stack unwind before putting alert. i'm not @ sure can reliably (cross-browser , os) prevent form submission cancelling default action of keydown
. said working, , if works in target browsers, great, but...
Comments
Post a Comment