Prevent users from submitting a form by hitting Enter

后端 未结 30 3264
感动是毒
感动是毒 2020-11-21 05:13

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don\'t know why) and accidentally submitting the survey (form) without clicki

相关标签:
30条回答
  • 2020-11-21 05:46

    This is the perfect way, You will be not redirected from your page

    $('form input').keydown(function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
    });
    
    0 讨论(0)
  • 2020-11-21 05:48

    Using Javascript (without checking any input field):

    <script>
    window.addEventListener('keydown', function(e) {
        if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    }, true);
    </script>
    

    If someone wants to apply this on specific fields, for example input type text:

    <script>
    window.addEventListener('keydown', function(e) {
        if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
            if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
                e.preventDefault();
                return false;
            }
        }
    }, true);
    </script>
    

    This works well in my case.

    0 讨论(0)
  • 2020-11-21 05:49

    ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

    window.addEventListener('keydown', function(event) {
      //set default value for variable that will hold the status of keypress
      pressedEnter = false;
    
      //if user pressed enter, set the variable to true
      if (event.keyCode == 13)
        pressedEnter = true;
    
      //we want forms to disable submit for a tenth of a second only
      setTimeout(function() {
        pressedEnter = false;
      }, 100)
    
    })
    
    //find all forms
    var forms = document.getElementsByTagName('form')
    
    //loop through forms
    for (i = 0; i < forms.length; i++) {
      //listen to submit event
      forms[i].addEventListener('submit', function(e) {
        //if user just pressed enter, stop the submit event
        if (pressedEnter == true) {
          updateLog('Form prevented from submit.')
          e.preventDefault();
          return false;
        }
    
        updateLog('Form submitted.')
      })
    }
    
    var log = document.getElementById('log')
    updateLog = function(msg) {
      log.innerText = msg
    }
    input,
    textarea {
      display: inline-block;
      margin-bottom: 1em;
      border: 1px solid #6f6f6f;
      padding: 5px;
      border-radius: 2px;
      width: 90%;
      font-size: 14px;
    }
    
    input[type=submit] {
      background: lightblue;
      color: #fff;
    }
    <form>
      <p>Sample textarea (try enter key):</p>
      <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>
      <p>Sample textfield (try enter key):</p>
      <input type="text" placeholder="" />
      <br/>
      <input type="submit" value="Save" />
      <h3 id="log"></h3>
    </form>

    0 讨论(0)
  • 2020-11-21 05:50

    Something I have not seen answered here: when you tab through the elements on the page, pressing Enter when you get to the submit button will trigger the onsubmit handler on the form, but it will record the event as a MouseEvent. Here is my short solution to cover most bases:

    This is not a jQuery-related answer

    HTML

    <form onsubmit="return false;" method=post>
      <input type="text" /><br />
      <input type="button" onclick="this.form.submit()" value="submit via mouse or keyboard" />
      <input type="button" onclick="submitMouseOnly(event)" value="submit via mouse only" />
    </form>
    

    JavaScript

    window.submitMouseOnly=function(evt){
        let allow=(evt instanceof MouseEvent) && evt.x>0 && evt.y>0 && evt.screenX > 0 && evt.screenY > 0;
        if(allow)(evt.tagName=='FORM'?evt.target:evt.target.form).submit();
    }
    

    To find a working example: https://jsfiddle.net/nemesarial/6rhogva2/

    0 讨论(0)
  • 2020-11-21 05:50

    This has worked for me in all browsers after much frustration with other solutions. The name_space outer function is just to stay away from declaring globals, something I also recommend.

    $(function() {window.name_space = new name_space();}); //jquery doc ready
    function name_space() {
        this.is_ie = (navigator.userAgent.indexOf("MSIE") !== -1);
    
        this.stifle = function(event) {
            event.cancelBubble;
            event.returnValue = false;
            if(this.is_ie === false) {
                event.preventDefault();
            }
            return false;
        }
    
        this.on_enter = function(func) {
            function catch_key(e) {
                var enter = 13;
                if(!e) {
                    var e = event;
                }
                keynum = GetKeyNum(e);
                if (keynum === enter) {
                    if(func !== undefined && func !== null) {
                        func();
                    }
                    return name_space.stifle(e);
                }
                return true; // submit
            }
    
            if (window.Event) {
                window.captureEvents(Event.KEYDOWN);
                window.onkeydown = catch_key;
            }
            else {
                document.onkeydown = catch_key;
            }
    
            if(name_space.is_ie === false) {
                document.onkeypress = catch_key;    
            }
        }
    }
    

    Sample use:

    $(function() {
        name_space.on_enter(
            function () {alert('hola!');}
        );
    });
    
    0 讨论(0)
  • 2020-11-21 05:51

    I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:

    <form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">
    

    The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.

    0 讨论(0)
提交回复
热议问题