Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling ENTER button in TextBox, ASP.NET

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

like image 965
usr-local-ΕΨΗΕΛΩΝ Avatar asked Dec 04 '10 19:12

usr-local-ΕΨΗΕΛΩΝ


2 Answers

Here is an easier way works great for ASP.NET:

Add this in your .aspx page

<script type="text/javascript">
        function clickButton(e, buttonid) {
            var evt = e ? e : window.event;
            var bt = document.getElementById(buttonid);
            if (bt) {
                if (evt.keyCode == 13) {
                    bt.click();
                    return false;
                }
            }
        }
</script>

And add this on the Page_Load in your aspx.cs file

textbox1.Attributes.Add("onkeypress", "return clickButton(event,'" + buttonName1.ClientID + "')");
like image 162
Apollo Avatar answered Oct 15 '22 09:10

Apollo


You could try this:

<html>
<head>
<script type="text/javascript">
function test(e){
 var keynum;

if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}   
if(keynum==13) __doPostback('yourButtonId', '');
}
</script>
</head>
<body>
<input type="text" onkeypress="test(event)" />
</body>
</html>

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.

like image 21
joelt Avatar answered Oct 15 '22 10:10

joelt