kumar
kumar

Reputation: 209

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?

Upvotes: 0

Views: 672

Answers (5)

Andy Rose
Andy Rose

Reputation: 16974

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");
            }
        });

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

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

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100322

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
      }
  });

Upvotes: 0

Bharat Patil
Bharat Patil

Reputation: 1408

Try this one

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

Upvotes: 0

DanSingerman
DanSingerman

Reputation: 36502

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

By then your form has long since posted.

Upvotes: 0

Related Questions