How to prevent a textbox causing a postback

This is a rather annoying situation with a simple solution. Your page contains a textbox and if you press the enter key while the textbox has focus, it will trigger a POST request to the server. Unfortunately for the user, it’s pure habit to do this – you type in something and immediately hit Enter while the textbox still has focus. The Google home page is a classic example.

The Solution
The trick to stop this happening is to catch the textbox’s key down event and either ignore or perform some other action. So the first thing to do is assign a key-down handler to the textbox in your page markup. In this example I’m using an HTML input control but it works exactly the same way for an ASP.NET TextBox server control (because the resulting markup sent to the client is still effectively the same).

<input type="text" onkeydown="javascript:return textboxKeyDown(event);" />

Now you just need to add the corresponding JavaScript event handler. Forinstance, if there’s a control on the page that does something with the user-entered text (e.g. posts it via an AJAX call) then call that same function before returning false. This will give consistent behaviour whether the user hits the enter key while the textbox has focus, or clicks the button.

When the event handler returns false, the automatic POST request caused by the key down event is simply cancelled.

Advertisements

About Phil Munro

I have been developing commercial desktop and distributed web applications with Microsoft technologies since 1997.
This entry was posted in Javascript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s