Darrell Norton's Blog [MVP]

Sponsors

The Lounge

News

  • Darrell Norton pic

    MVP logo

    View Darrell Norton's profile on LinkedIn

    Currently Reading:

    weewar.com

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Submitting default buttons when the user presses the Enter key - finally!

One of the hardest things in web development is getting a certain button to submit if you have more than one button on the page.  Andy Smith, of Metabuilders fame, has one that works for late-model browsers.

Due to rather strict client requirements for a public e-commerce site, I needed something that went further back in browser history.  I found a code sample from Janus Kamp Hansen that only worked for IE.

I extended it to work with Mozilla and Netscape 6+, then added some more code to get it to work with most Netscape 4+ browsers.  Then I tweaked the performance a bit, and that’s it!  A fast, easy-to-use code snippet to force specific submit buttons to fire from developer-determined textboxes.

First, copy this method into an easily accessible place:

public void SetDefaultButton(Page page, TextBox textControl, Button defaultButton)

{

      // Sets default buttons.

      // Originally created by Janus Kamp Hansen - http://www.kamp-hansen.dk

      // Extended by Darrell Norton - http://dotnetjunkies.com/weblog/darrell.norton/

      //   -- added Mozilla support, fixed a few issues, improved performance

      string theScript = @"

<SCRIPT language=""javascript"">

<!--

function fnTrapKD(btn, event){

 if (document.all){

  if (event.keyCode == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if (document.getElementById){

  if (event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

 else if(document.layers){

  if(event.which == 13){

   event.returnValue=false;

   event.cancel = true;

   btn.click();

  }

 }

}

// -->

</SCRIPT>";

 

      Page.RegisterStartupScript("ForceDefaultToScript", theScript);

      textControl.Attributes.Add("onkeydown", "fnTrapKD(" + defaultButton.ClientID + ",event)");

}

This code registers the given script with the Page.  Then it adds an attribute to the textbox, which in this case is an onKeyDown event that calls the fnTrapKD function with the button’s clientID (it’s HTML ID in the rendered HTML) and the event.  I had to pass the event in because Netscape/Mozilla browsers can’t catch this kind of event unless you pass it in to the function.  IE can access the event from the document object, but we want something nice and cross-browser compatible.

The document.all if statement covers IE.  The document.getElementById covers Netscape 6+ and Mozilla browsers.  The document.layers if statement works with Netscape 4+.

Now add a line of code linking each textbox that you want with a certain submit button.  For example:

      SetDefaultButton(this.Page, TextBox1, Button1);

      SetDefaultButton(this.Page, TextBox2, Button2);
      SetDefaultButton(this.Page, TextBox3, Button3);

I usually put that in the Page_Load, since the Page.RegisterStartupScript method will ignore duplicate scripts.  Now it is simply a matter of making a call to SetDefaultButton for each textbox-submit button association.

I haven’t tested this extensively yet, and some of the JavaScript may be unnecessary.  And considering the number of Netscape 4 versions (and their bugginess), it probably doesn’t work on all of them.  But it works (for now).  And at least making an attempt at Netscape 4+ and IE 5+ will cover 99% of my site’s web browsers.

UPDATE:  Released v1.1 which fixes a few errors and offers better code samples.  See the GotDotNet workspace for full details.
UPDATE:  Updated the code snippets on this page (they are correct in the code sample download).
UPDATE:  Released v2.0 which works with ImageButtons, DropDownLists, and most other form elements, at the cost of Netscape 4 support.


Posted 03-03-2004 5:31 PM by Darrell Norton

[Advertisement]

Comments

Aleš Potočnik wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-06-2005 7:35 AM
Hi.
It's a great code snipet. And it works instantly upon implementation.
However, I still had some problems with Mozilla Firefox browser. Before I implemented this function I used textbox's onKeyDown="doSomething(); event.returnCode=false;" It worked fine in IE browsers. But when tested in Firefox it still produced some code handling after doSomething(). This is probably coused by .net.
Now I implemented this sample and again, the Firefox still does something afterwards. I'm implementing this in a rainbow portal (www.rainbowportal.net). Maby there's something wrong with the rainbow framework.
I extensively tested the html code produced. The "event.returnCode" and "event.cancel" have, as it seems - no efect on the afterwards event handling. I tested the execution - if the button onClick event is actualy called. It's called from IE and FF. The only diference is that in IE the event gets canceled and in FF not.

Anyways, thanks for a great starting point and thanks for sharing it.
Krzysztof Slazak wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-08-2005 1:57 AM
Hi Ales.

Try doing 2 modifications:

1. Add "return false;" statement after calling "btn.click();" in function fnTrapKD.

2. When adding an attribute to textControl, do it like this:
textControl.Attributes.Add("onkeydown", "return fnTrapKD(" + defaultButton.ClientID + ",event)");

I think this might help.

Krzysztof
willy martinez wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-09-2005 2:08 PM
It's a great code snipet, but when you use a validator control doesn´t work do you have any idea?
Darrell wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-09-2005 2:40 PM
Set CausesValidation = false for the submit button.
NS wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-10-2005 11:28 AM
I am trying to implement this code but my textbox and button are placed on the usercontrol so when button is rendered on the page it takes the name with different Name and ID values.

Any idea how to make this working in this scenario?

Any help would be highly appreciated.
becks wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-10-2005 4:13 PM
hmmm what if the textbox is part of a datagrid? ie:

<asp:TemplateColumn HeaderText="Username">
<ItemTemplate>
<asp:textbox Width="100%" id=txtusr runat="server"> </asp:textbox>
</ItemTemplate>
</asp:TemplateColumn>

ive tried doing something like this:
SetDefaultButton(Me.Page, DirectCast(dg.Items.Item(0), TextBox), btnSaveUsers)

but it dont work, any ideas?
becks wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-10-2005 4:28 PM
ok i got it just do this in the page_load

Dim dgitem As DataGridItem
Dim usr As TextBox

For Each dgitem In dg.Items
usr = dgitem.FindControl("txtusr")
Next

SetDefaultButton(Me.Page, usr, btnSaveUsers)
Brian wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-24-2005 5:17 AM
Scenario:
Script runs on IE 5.5+ which uses autocomplete. The user selects an entry in the drop down menu generated by the browser and presses <enter> key.

Problem:
The <enter> used for selecting an entry in the dropdown autocomplete is trapped and binds to the button. Instead it should be ignored.

All scripts regarding binds I've seen have this problem. Any suggestions on how to detect this special case?
Darrell wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 02-24-2005 6:04 AM
If you're using my code, just don't call the SetDefaultButton method with the dropdownlist control. Otherwise you can add a check in the JavaScript to ignore the enter key only if it is the dropdownlist.
TrackBack wrote Utilizzare il tasto
on 02-25-2005 3:21 AM
Brian wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 03-04-2005 2:47 AM
I was a bit onclear in my previous post. What I meant was that the problem exists with TextBoxes as well: when entering text in the box IE will autogenerate previously entered information in a dropdown - not a DropDownList in ASP.NET sense). Disabling the script for DropDownList will therefore not solve the problem. A check - on the other hand - would indeed.. but what command (IE specific) can detect if the autocomplete dropdown is activated?
Darrell wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 03-04-2005 6:03 AM
Add this attribute to the HTML of the textbox autocomplete="off".

If you want to turn off autocomplete for the entire form, add it to the form tag.
Brian wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 03-06-2005 2:37 AM
Hi Darrell,
I am familiar with this command, but thank You anyway for pointing it out to me. I don't want to turn off autocomplete but instead treat it as a special case.. is this possible?
Darrell wrote re: Submitting default buttons when the user presses the Enter key - finally!
on 03-09-2005 5:54 AM
Brian - I was hoping to have time to work on this, but apparently I am not anytime soon. However, in doing some research I came upon this statement from MSDN:
"To determine when a user updates the content of a field from the AutoComplete dialog box, use the onpropertychange event, rather than the onchange event, because the onchange event does not fire."

My guess is you should check in the OnKeyPress event to see if it is also an OnPropertyChange event, then don't do anything. If not, then submit the form.

The relavent links on MSDN are:
http://msdn.microsoft.com/workshop/author/forms/autocomplete_ovr.asp
and
http://msdn.microsoft.com/workshop/author/dhtml/reference/events/onpropertychange.asp
Colt Kwong's Blog wrote re: Default Button / Press Enter Key in Web Form
on 04-08-2005 6:34 PM
VB-tech weblog wrote re: asp.net : get a button to submit when a user presses enter in a textbox
on 05-27-2005 10:00 AM
wrote Varios DefaultButton para un mismo Formulario web. Propuesta
on 04-12-2008 12:57 AM

En una pregunta de hoy en los foros de MSDN el tema era como tener mas de un DefaultButton por formulario