How to fix Enter key press issue in multiline textarea with defaultbutton defined in asp.net page

As I posted on How to set the DefaultButton in a Page Based on ASP.NET Master Page, a DefaultButton property has been defined in the ASP.NET pages which can fire the onClick event in asp.net page when the Enter key is pressed. But I got another new problem: when I pressed Return key in a multiline textbox, a new line was not generated. Instead, the in-completed form was tried to be submitted.

And I found out it caused the problem only when I used Firefox, and I tested it in IE everything was fine.

According to the Microsoft Online Support, there is a in-compatible issue in ASP.net 2.0 generated Javascript.

In the function WebForm_FireDefaultButton(event, target) of ASP.net Javascript, it uses event.srcElement to capture the Key element of the Key Entering event from the user. While in Firefox, this Javascript method should be event.target instead.

Here is the fix or workaround before Microsoft releases its own.

  1. Copy and paste the following Javascript code in the Notepad.
  2. Save as a javascipt file (like DefautlBtnFix.js).
  3. Call this file in your ASP.net file, like using <script language=”javascript” type=”text/javascript” src=”DefaultBtnFix.js”></script> (you might put it in the bottom of your master page file)

var __defaultFired = false;

function WebForm_FireDefaultButton(event, target) {

var element = event.target || event.srcElement;

if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == “textarea”))) {

var defaultButton;

if (__nonMSDOMBrowser) {

defaultButton = document.getElementById(target);

}

else {

defaultButton = document.all[target];

}

if (defaultButton && typeof(defaultButton.click) != “undefined”) {

defaultButton.click();

event.cancelBubble = true;

if (event.stopPropagation) event.stopPropagation();

return false;

}

}

return true;

}

Good luck.

Reference URLs:
Walter Wang ( wawang at online.microsoft.com, remove ‘online.’)
Hints and Tips

  • Share/Bookmark
Tags: , , , , ,

Related posts

1 Response to “How to fix Enter key press issue in multiline textarea with defaultbutton defined in asp.net page”


  • Thank you this works brilliantly. The only other solution I could find to this problem was adding some javascript to each textarea …which would have been a nightmare across a large project. You’re a life-saver.

    [Reply]

Leave a Reply



Get Adobe Flash playerPlugin by wpburn.com wordpress themes