DForck42 DForck42 - 6 months ago 18
Javascript Question

Prevent Users from submitting 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. Is there a way to prevent this? I'm using html, php 5.2.9, and jquery on the survey.

Answer

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