Disabling enter key for form

后端 未结 12 801
深忆病人
深忆病人 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 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) {
        }
    }
    

提交回复
热议问题