开发者

Clean way to prevent enter button submitting a form

I've seen a lot of Javascript solutions to do this, but I'm sure there must be an easier way.

I have a really simple form - one multiline textbox and a submit button. I want the user to be able to submit "formatted" text (i.e. like an email, with paragraphs, new lines etc)

H开发者_高级运维owever, when the user hits Enter to put in a carriage return it submits the form.

I'm there there must be a property or something that controls this, as this must be a common issue. Javascript as a solution seems a bit too complex.


Set the UseSubmitBehavior property on the submit button to FALSE. (found the solution here)


The following code solved my issue:

http://www.itorian.com/2012/07/stop-from-submission-posting-on-enter.html

<script type="text/javascript">
    //Stop Form Submission of Enter Key Press
    function stopRKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopRKey;
</script>

Put this in the master page or just in the pages that you want.


Use Submit behavior didn't work for me but this

 $(function () {
        $(window).keydown(function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                return false;
            }
        });
    })

worked for me


You could set the DefaultButton on the Form or the Panel surrounding your TextBox to an invisible(display:none) Button. On this way you have full control what happens when user hits enter-key without (browser-dependent) Javascript. If you don't handle its onclick-event, the enter-key will be suppressed.

http://geekswithblogs.net/ranganh/archive/2006/04/12/74951.aspx


Did u try this? - Enter key in textarea


Similar to the answer of Max, but showing complete code:

    function EnterKeyFilter() {
        if (window.event.keyCode == 13) {
            event.returnValue = false
            event.cancel = true
        }
    }
    window.addEventListener('keydown', EnterKeyFilter)
</script>

Also similar to other answers, of course, otherwise it wouldn't work, but possibly simpler.


In HTML front end just replace body tag with body onkeydown = "return (event.keyCode!=13)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜