Prevent users from submitting a form by hitting Enter

后端 未结 30 3438
感动是毒
感动是毒 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: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!');}
        );
    });
    

提交回复
热议问题