Server generated code to make the enter key submit the form

Discussion in 'ASP .Net' started by Wysiwyg, Feb 9, 2005.

  1. Wysiwyg

    Wysiwyg Guest

    Hi, I just thought I'd post this since I didn't see anyone else doing it
    this way. I wanted to be able to force the enter key to submit the form
    without manually changing the html form,

    In my custom base page class I added a generic method I can call to handle
    the user pressing the enter key when I want it to submit the form. This sets
    the destination button on a for the entire form rather than on a
    field-by-field basis; i.e. it's not for a single text box. The advantage for
    me is that I didn't require modifications to the web page itself since I
    programatically added the event to the body.

    public void HandleEnterKey(Button btnSubmit)
    {
    string strJava =
    "<script language='javascript'>\n" +
    "function CheckSubmit() {\n" +
    "\tif (event.keyCode == 13) {\n" +
    "\t\tctl = document.getElementById('" + btnSubmit.ClientID + "');\n" +
    "\t\tif (ctl != null)\n" +
    "\t\t\tctl.focus();\n" +
    "\t}\n" +
    "}\n" +
    "document.body.onkeypress = CheckSubmit;\n" +
    "</script>";
    Page.RegisterStartupScript("checksubmit",strJava);
    }

    The \t (tab) and \n (new line) in the java string just formats the generated
    html source to be readable.

    Whenever I need this functionality in a page I just invoke it when the input
    form is displayed with a line like:

    HandleEnterKey(BtnSubmit);

    Where BtnSubmit is the actual submit button control rather than a string
    value in the off chance that the actual generated html modifies the control
    name. I check to make sure the button exists since the button may be hidden
    with a command that occurs after I create the client code; i.e. the input
    form is hidden and a summary is displayed after the form is submitted.

    Bill
    Wysiwyg, Feb 9, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Megha Vishwanath
    Replies:
    2
    Views:
    9,799
    tutorialsmaster
    Oct 2, 2009
  2. Alexboy
    Replies:
    2
    Views:
    6,097
    Disco Octopus
    Nov 14, 2005
  3. BrianDH

    Enter Key H*ll, control enter key submit button

    BrianDH, Jan 12, 2005, in forum: ASP .Net Web Controls
    Replies:
    3
    Views:
    371
    Anders Matthiessen
    Jan 12, 2005
  4. Megha Vishwanath
    Replies:
    3
    Views:
    682
    Megha Vishwanath
    Jul 20, 2004
  5. Alexboy
    Replies:
    1
    Views:
    271
    web.dev
    Nov 14, 2005
Loading...

Share This Page