Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

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.

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

13 Responses to Submitting default buttons when the user presses the Enter key – finally!

  1. Darrell says:

    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

  2. Brian says:

    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?

  3. Darrell says:

    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.

  4. Brian says:

    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?

  5. Darrell says:

    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.

  6. Brian says:

    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?

  7. becks says:

    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)

  8. becks says:

    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?

  9. NS says:

    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.

  10. Darrell says:

    Set CausesValidation = false for the submit button.

  11. willy martinez says:

    It’s a great code snipet, but when you use a validator control doesn´t work do you have any idea?

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>