Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent input field inside form from submitting when enter key is pressed? [duplicate]

I have a simple form.

Input fields, checkboxes, radio buttons and finally SUBMIT button.

I use jQuery to perform AJAX validation, however when a user presses ENTER inside the input field it submits the form!

How do I stop this from happening on this form (not all input fields)?

like image 269
st4ck0v3rfl0w Avatar asked Feb 26 '23 15:02

st4ck0v3rfl0w


2 Answers

suppose your inputs for which you don't want to submit on enter has class noSubmit then use this code:

$(function(){
     $("input.noSubmit").keypress(function(e){
         var k=e.keyCode || e.which;
         if(k==13){
             e.preventDefault();
         }
     });
 });
like image 126
TheVillageIdiot Avatar answered Mar 01 '23 05:03

TheVillageIdiot


You can use the onsubmit handler to trap form submission and perform validation:

<form onsubmit="return validate();">
...
</form>

<script type="text/javascript">
function validate() {
  // return true to submit form or false to stop
}
</script>
like image 34
casablanca Avatar answered Mar 01 '23 04:03

casablanca