Prevent users from submitting a form by hitting Enter

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

    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


    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/

提交回复
热议问题