Disabling enter key for form

后端 未结 12 789
深忆病人
深忆病人 2020-12-04 21:07

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The cod

相关标签:
12条回答
  • 2020-12-04 21:55

    You can try something like this, if you use jQuery.

    $("form").bind("keydown", function(e) {
       if (e.keyCode === 13) return false;
     });
    

    That will wait for a keydown, if it is Enter, it will do nothing.

    0 讨论(0)
  • 2020-12-04 22:00

    The solution is so simple:

    Replace type "Submit" with button

    <input type="button" value="Submit" onclick="this.form.submit()" />
    
    0 讨论(0)
  • 2020-12-04 22:01

    The better way I found here:

    Dream.In.Code

    action="javascript: void(0)" or action="return false;" (doesn't work on me)

    0 讨论(0)
  • 2020-12-04 22:02

    this is in pure javascript

            document.addEventListener('keypress', function (e) {
                if (e.keyCode === 13 || e.which === 13) {
                    e.preventDefault();
                    return false;
                }
                
            });

    0 讨论(0)
  • 2020-12-04 22:02

    I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()

    /*
     * Prevents default behavior of pushing enter button. This method doesn't work,
     * if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
     * the input. So method should be attached directly to the input 'onkeydown'
     */
    function preventEnterKey(e) {
        // W3C (Chrome|FF) || IE
        e = e || window.event;
        var keycode = e.which || e.keyCode;
        if (keycode == 13) { // Key code of enter button
            // Cancel default action
            if (e.preventDefault) { // W3C
                e.preventDefault();
            } else { // IE
                e.returnValue = false;
            }
            // Cancel visible action
            if (e.stopPropagation) { // W3C
                e.stopPropagation();
            } else { // IE
                e.cancelBubble = true;
            }
            // We don't need anything else
            return false;
        }
    }
    /* Disable enter key for all inputs of the document */
    function disableAllInputs() {
        try {
            var els = document.getElementsByTagName('input');
            if (els) {
                for ( var i = 0; i < els.length; i++) {
                    els[i].onkeydown = preventEnterKey;
                }
            }
        } catch (e) {
        }
    }
    
    0 讨论(0)
  • 2020-12-04 22:03

    if you use jQuery, its quite simple. Here you go

    $(document).keypress(
      function(event){
        if (event.which == '13') {
          event.preventDefault();
        }
    });
    
    0 讨论(0)
提交回复
热议问题