Hello Friends, Today I am going to share how we can prevent form submission on pressing enter on specific field of a form. Actually when we press enter inĀ fields of a form (form tag in html), it triggers form submission by default, but sometime we don’t want form to be submitted on pressing enter on some specific fields, actually recently I was developing a project in which I faced same situation where some fields are just used for generating some rows in a table, So I thought to share it with everyone. So here is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<html> <head> <title>Preventing Form Submission on Pressing Enter on Specific Elements of Form</title> </head> <body> <form action=""> <input name="input1" id="input1" placeholder="Don't Submit on Enter"/> <input name="input2" id="input2" placeholder="Submit on Enter"/> <input type="submit" name="submit" value="Submit"/> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $("#input1").on("keypress", function(e) { //both keypress and keydown can be used here but not keyup if(e.keyCode == '13') { e.preventDefault(); alert("form submission stopped"); } }) </script> </body> </html> |
Output
Thanks for visiting, please do share if you like it
Comments