Prevent users from submitting a form by hitting Enter

后端 未结 30 4434
感动是毒
感动是毒 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:53

    I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

        var preventSubmit = function(event) {
            if(event.keyCode == 13) {
                console.log("caught ya!");
                event.preventDefault();
                //event.stopPropagation();
                return false;
            }
        }
        $("#search").keypress(preventSubmit);
        $("#search").keydown(preventSubmit);
        $("#search").keyup(preventSubmit);
    

    You can combine all the above into a nice compact version:

        $('#search').bind('keypress keydown keyup', function(e){
           if(e.keyCode == 13) { e.preventDefault(); }
        });
    

提交回复
热议问题