Server generated code to make the enter key submit the form

W

Wysiwyg

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top