views:

101

answers:

5

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?

A: 

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

By then your form has long since posted.

DanSingerman
But aren't alert boxes "synchronous"? (You know what I mean, heh...)
Deniz Dogan
@Deniz: "Blocking" is the word you were looking for. And yes, they are.
T.J. Crowder
@deniz, but it is blocking something that is preventing the default behaviour. Hence you get the default behavior, which is form submission.
DanSingerman
[Here's an example.](http://jsfiddle.net/b9L5c/) The `return false;` still prevents the form submission. [Or a similar example](http://jsfiddle.net/b9L5c/1/) using a link. The href is never visited.
patrick dw
A: 

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");
            }
        });
Andy Rose
preventDefault() call also won't work. Looks like browser calling all click event handlers asynchronously. Is it true?
kumar
@kumar - sorry, there was a type in my code. e.preventDefault() should work.
Andy Rose
+1  A: 

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

T.J. Crowder
In my original piece of code, If I don't use alert it works (At least in IE and Firefox I tested), My question was not how to stop form posting (For this I can use different code path), but to know what alert is causing it to malfunction if it is called in the middle before returning false.
kumar
@kumar: Yeah. I would have expected the alert to make no difference (other than the obvious), that's what it's supposed to do. It seems as though the browser you were using is not letting the event handler block submission if it does something requiring an input handler (which sounds like a very IE weirdness to me -- is that what you were using by any chance?). (cont'd)
T.J. Crowder
@kumar: (continuing) If preventing the default of `keydown` should prevent the form submission, then the form shouldn't be submitted until the `keydown` event handlers have all completed, and the `alert` should be preventing this one completing. What you're seeing is definitely browser-specific. **I** would call it a bug in the browser, but I don't make the rules. :-)
T.J. Crowder
Thanks. I just wanted to confirm that using alert in the middle can cause weird behavior.
kumar
A: 

Try this one

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

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