Wednesday, January 23, 2019

jquery - 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. 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;
}

});
});

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...