Prevent users from submitting a form by hitting Enter

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

    You can use a method such as

    $(document).ready(function() {
      $(window).keydown(function(event){
        if(event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });
    });
    

    In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:

    function validationFunction() {
      $('input').each(function() {
        ...
    
      }
      if(good) {
        return true;
      }
      return false;
    }
    
    $(document).ready(function() {
      $(window).keydown(function(event){
        if( (event.keyCode == 13) && (validationFunction() == false) ) {
          event.preventDefault();
          return false;
        }
      });
    });
    

提交回复
热议问题