Search code examples
asp.netformstextboxenteronkeypress

ASP.NET - Enter disabled on form prevents enter (new line) in multiline textbox


I have a master page with a form:

<form id="FormMaster" runat="server" onkeypress="return (event.keyCode != 13)">

The enter key disabled is a must. However, now the enter key is disabled in textboxes as well, and that is a problem.

Is there a way I can enable enter key for textboxes inside this form?

Thanks.


Solution

  • Simply don't disable "form enter" using the form keypress event.

    If there is more than one input/control, browsers shouldn't "submit on enter", but rather only when enter is pressed while a submit button is focused .. (which means you can use a similar approach to disable enter on the submit button or make it unfocusable in such cases).

    If you must use the keypress event of the form, look at the Event Target property, and only perform the event suppression if not one of the appropriate multi-line inputs (aka textarea elements).

    if ((event.target || event.srcElement).nodeName != "TEXTAREA") {
       // not textarea (multi-line input), suppress as original
    }