Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

jquery - 通过按Enter阻止用户提交表单(Prevent users from submitting a form by hitting 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.

(我在网站上进行了一项调查,用户单击Enter键(我不知道为什么),然后不按提交按钮就意外提交了调查(表单),似乎存在一些问题。)

Is there a way to prevent this?

(有办法防止这种情况吗?)

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

(我在调查中使用的是HTML,PHP 5.2.9和jQuery。)

  ask by DForck42 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...