按 Enter 阻止用户提交表单

2022-01-30 00:00:00 forms jquery html form-submit

我在一个网站上进行了一项调查,用户按 Enter 键(我不知道为什么)并在未点击提交按钮的情况下意外提交了调查(表单)似乎存在一些问题.有没有办法防止这种情况?

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 clicking the submit button. Is there a way to prevent this?

我在调查中使用 HTML、PHP 5.2.9 和 jQuery.

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

推荐答案

可以使用诸如

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

在阅读原始帖子的评论时,使其更实用,并允许人们在完成所有字段后按Enter:

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;
    }
  });
});

相关文章