Hit Enter and Post Back with JavaScript

Give your textboxes the power to post back.

  Many times I've wanted users to be able to type some text in a few input fields, hit Enter, and get a postback event. If you've tried it out, you know it just doesn't work. I can think of at least one good reason this feature is missing: To capture the Enter key, the textbox needs some client JavaScript code to access the underlying browser's event object model. An event object model simply doesn't exist for browsers older than Internet Explorer 4.0. Coding a similar feature in a commonly used server control such as a TextBox would make the code much more complex because it's browser-dependent. In general, complexity is not a problem for professional coders. However, as Albert Einstein said, "Make everything as simple as possible, but not simpler." For articles on JavaScript, see "How to Structure JavaScript Code, Part 1" and "Structuring JavaScript Code in HTML5 Applications, Part 2."

The upshot is that hitting Enter on a textbox and having the control post back is not "mission impossible." If you want to give it a try, though, be prepared to face quite a few programming issues.


Design a TextBox that Posts Back

Let's start by writing a pretty simple page that contains only one textbox. Run the page, click on the field to give it focus, and press Enter. Amazingly enough, the page posts back. At this point, you might think that most of the work is done and that only one problem remains: how to intercept the event and run some server-side code. Unfortunately, you have another problem. Try adding a second textbox to the page. With two or more textboxes, the page won't post back when you press the Enter key from within any of them.

In this article, I'll show you how to build a custom TextBox control that captures the Enter key, posts back to the server, and raises an event to the code. And as icing on the cake, I'll make this control support server- and client-side validation. This code shows the prototype of the new class at this time:

namespace AspNetPro


   public class PostTextBox : TextBox  


       public bool CanPostBack;

      protected override void OnLoad(EventArgs e);



CanPostBack is a Boolean property that toggles the control's capability to capture the Enter key and post back on and off. It is set to false by default. The implementation of the property is nothing special. It simply gets and sets the value from and to the view state. The new control's core code resides in the OnLoad overridden method. In this method, the control accomplishes basically three tasks. First, it checks the value of CanPostBack and exits if it is found to be False. In this case, the custom TextBox behaves just like the parent class. Next, the control verifies the browser's capabilities to see if the necessary script can be run successfully. The key point is that the script code needs to access the window.event object in the browser's HTML object model. As I mentioned, this object doesn't exist in versions of Internet Explorer older than 4.0. Likewise, it isn't supported in Netscape 4.x browsers. For this reason, I've limited the supported browsers to Internet Explorer 4.0 and newer:

private bool TestBrowser()


   HttpBrowserCapabilities caps = Page.Request.Browser;

   _fBrowserCapsTested = true;

   if (caps.Browser.ToUpper().IndexOf("IE") > -1)

      return caps.MajorVersion >3;  


   return false;


Finally, the control injects the script code that captures the Enter key and posts back. The OnKeyPress attribute is added to the textbox control to reference this script code:

The CaptureEnter JavaScript function fulfills two key requirements. It ensures that the last typed key is Enter (ASCII code 13) and runs the standard ASP.NET postback procedure. This listing shows the necessary script code:

function CaptureEnter(ctl) {

   var key = window.event.keyCode;

   if (key == 13) {

      __doPostBack(ctl.name, '');




The ctl parameter is the instance of the JavaScript object that represents the textbox in the browser's HTML object model. 

In ASP.NET, the Page object's GetPostBackEventReference method takes a control instance and returns the JavaScript function call that makes it post back. Typically, this method returns a string that looks like this:

__doPostBack('PostTextBox1', '')

You should always use this method to make sure that your code survives any changes to the client-side support in future versions of ASP.NET. However, in this case I prefer to make assumptions on the syntax of __doPostBack and produce a more compact block of JavaScript code in the final page. The CaptureEnter function shown above is control-independent and can serve all instances of the PostTextBox class you have in the page. In contrast, GetPostBackEventReference can only generate a postback function call for a given control instance. The UniqueID property of the control becomes the first argument of __doPostBack. When you use GetPostBackEventReference, you end up with a copy of CaptureEvent for each control in the page. Worse yet, these functions differ only in the name of the first parameter of __doPostBack.

If the forward compatibility of code that explicitly uses __doPostBack is a concern, rest easy. I tested the sample code for this article with the ASP.NET 2.0 alpha and it works just great. Although ASP.NET 2.0 is still in the works, I believe that any worries you have about __doPostBack can be delayed until ASP.NET 3.0! 

Capture the Enter Key

Generating a block of JavaScript code is a matter of accumulating some text in a StringBuilder object. You should add both the opening and closing