I have the following problem in ASP.NET: there is a form that contains a textbox and a button next to it that is supposed to be pressed by the user after filling the box (sample on http://www.burnthespam.info, click "Pick your one", or when using ReCaptcha in a popup). Often, instead, users press ENTER
key to submit the form.
This doesn't cause the click event on the button to be triggered and possibly cause an unexpected behaviour. In burnthespam, I "tried" to solve by checking if there is data inside the text box (but now if you do something different than pressing ENTER
it's like you pressed it) to workaround it.
Do you know if there is another way to handle the form submission with ENTER
key, or a Javascript snippet that when you press ENTER
presses the button I like?
EDIT
I want to handle the ENTER key event on the server-side, ie. I already have
protected void button_Click(object sender, EventArgs e)
{
Response.Redirect(...);
}
I want that method to be called not only when I submit the form using the button (click or space with it highlighted) but also when a user presses ENTER
when focusing the text-box
EDIT 2
Do you know if it's possible to programmatically click a button in Javascript? Maybe it's not possible to prevent phishing/spamming (see Facebook and "share to friends" for example) but I still would like to ask...
There some ways you can set a default button using the form object DefaultButton property or the DefaultButton property of a panel, but I have found them to be unreliable in the past in various browsers so usually I rely on javascript.
The only downside to this code is you have to turn off event validation with a page directive, but it should fire off click events, and trigger validators and all that.
Here is an example the code that we use. Normally I would put the register function in a utility class, but for this example it is in the page code. Try this out.
You could try this:
You'll need to replace 'yourButtonId' with the ID that is rendered in the markup for your button, ie the ClientID property in your .NET code. The __doPostback function is the one defined by .NET for handling all of its postbacks.
Here is an easier way works great for ASP.NET:
Add this in your .aspx page
And add this on the Page_Load in your aspx.cs file