6

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

3 Answers 3

4

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 + "')");
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

<%@ Page Language="C#" EnableEventValidation="false" %>

    <script runat="server">

        protected void cmdSubmit1_Click(object sender, EventArgs e)
        {
            litValue.Text = "Value 1 - You entered: " + txtValue1.Text;
        }
        protected void cmdSubmit2_Click(object sender, EventArgs e)
        {
            litValue.Text = "Value 2 - You entered: " + txtValue2.Text;
        }

        /// <summary>
        /// This function registers what button is clicked based on whatever control currently has focus
        /// so for example if the user password field has focus then you can cause the enter button to click
        /// if the enter key is pressed This works with ie and firefox as far as I know
        /// </summary>
        /// <param name="ControlWithFocus"></param>
        /// <param name="ControlToClick"></param>
        private void RegisterDefaultButton(System.Web.UI.Control ControlWithFocus, System.Web.UI.Control ControlToClick)
        {

            PostBackOptions p = new PostBackOptions(ControlToClick);
            p.PerformValidation = true;
            if (ControlToClick is Button)
            {
                p.ValidationGroup = ((Button)ControlToClick).ValidationGroup;
            }
            else if (ControlToClick is ImageButton)
            {
                p.ValidationGroup = ((ImageButton)ControlToClick).ValidationGroup;
            }
            else if (ControlToClick is LinkButton)
            {
                p.ValidationGroup = ((LinkButton)ControlToClick).ValidationGroup;
            }

            p.RequiresJavaScriptProtocol = false;

            AttributeCollection a = null;
            if (ControlWithFocus is HtmlControl)
            {
                a = ((System.Web.UI.HtmlControls.HtmlControl)ControlWithFocus).Attributes;
            }
            else if (ControlWithFocus is WebControl)
            {
                a = ((System.Web.UI.WebControls.WebControl)ControlWithFocus).Attributes;
            }

            if (a != null)
            {
                a["onKeyDown"] = string.Format("if (event.keyCode == 13) {{{0}}}"
                      , ControlToClick.Page.ClientScript.GetPostBackEventReference(p));
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterDefaultButton(txtValue1, cmdSubmit1);
            RegisterDefaultButton(txtValue2, cmdSubmit2);

        }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    </head>
    <body>
        <form id="form1" runat="server">
            Enter Value 1: <asp:TextBox ID="txtValue1" runat="server"></asp:TextBox>
            <br />
            Enter Value 2: <asp:TextBox ID="txtValue2" runat="server"></asp:TextBox>
            <br />
            <asp:Literal ID="litValue" runat="server"></asp:Literal>
            <asp:LinkButton ID="cmdSubmit1" runat="server" Visible="false" OnClick="cmdSubmit1_Click">Hidden Button 1</asp:LinkButton>
            <input id="cmdSubmit2" runat="server" visible="false" type="button" value="Hidden Button 2" onserverclick="cmdSubmit2_Click" />
        </form>
    </body>

4 Comments

I just noticed that your code, with little modifications, is simply IGNORED by IE8 while in Firefox works. Could it be due to the fact that the TextBox is a gaia:TextBox from Gaia AJAX WebWidgets and appears only after a postback? I double-checked that the generated HTML matches the one for button click, and I even didn't have to disable event validation (because in FF works), but I still get an empty HTTP (not AJAX like FF) postback
That is weird. If the javascript is there, and it looks like the javascript on the button and the button works, then one would think that the script on the textbox should have the same result. Is it possible that the gaia textbox is registering a onKeyDown event as well and that is causing it to not actually call the inline script. You should try the script debugger and see if the dopostback method is actually getting called.
Trying to use this ... I got it working by replacing the onkeyevent with just "if (event.keyCode == 13) { alert('go'); }" ... 'go' alert box pops up every time enter is clicked. But when I put your original code back in the page just refreshes and the LinkButton's click event is never called. Any ideas? (My code is almost identical to your example except I have just one LinkButton that both TextBoxes are calling) I'm testing this in IE9.
Was able to make it work by changing to the following: a["onKeyDown"] = "if (event.keyCode == 13) {" + ControlToClick.Page.ClientScript.GetPostBackEventReference(p) + "; return false; }"; The string.format() wasn't a problem, I just removed it during my testing and I got it working like this so left it as-is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.