开发者

JavaScript alert function behaviour

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 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...


The return false will not execute until the alert box has been dismissed.

By then your form has long since posted.


Try this one

 $("#TextBox1").keydown(function(e)
        {
            if(e.keyCode == 13)
            {
               e.preventDefault();
            }
        });


You should use e.preventDefault instead.

  $("#TextBox1").keydown(function(e)
  {
      if(e.keyCode == 13)
      {
          e.preventDefault(); // won't trigger default behavior

          alert("Hello"); // will work
      }
  });


if you really wanted this type of behaviour you could use event.preventDefault():

$("#TextBox1").keydown(function(e)
        {
            if(e.keyCode == 13)
            {
                e.preventDefault();
                alert("Hello");
            }
        });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜