How To Prevent Form Submission When User Presses the ENTER Key in TextBox?

 Copyright © 2007-2012 www.AspDotNetFaq.com

All we need to do to is to add JavaScript code to the OnKeyDown event of the TextBox instance that will prevent
Form submission if ENTER key is pressed.

Just add this code to your Page_Init method of the page where you want this behavior:

    protected void Page_Init(object sender, EventArgs e)

    {

        TextBox1.Attributes.Add("onkeydown",

        "if(event.which || event.keyCode){if (event.keyCode == 13) return false;}");

 

    }

Your TextBox will continue to work like before, but if user presses ENTER key, your
Web Form will not be submitted.
 



 Copyright © 2007-2012 www.AspDotNetFaq.com