How to prevent the submit form on enter key except the textarea using jQuery
Today we will show you how to prevent the submit form on enter key except the textarea using jQuery. In a real project, you may need to restrict the entry key to submit the form and if that form contains the textarea then we have to allow the enter key in textarea. So in this article, we will see how to prevent the submit form on enter using jQuery.
Checkout more articles on JavaScript
Let’s check the following jQuery code to prevent a form on enter.
1 2 3 4 5 6 7 8 | $(document).ready(function() { $(window).keydown(function(event) { if((event.keyCode == 13) && ($(event.target)[0] != $("textarea")[0])) { event.preventDefault(); return false; } }); }); |
Now we will use the above code in the HTML page to see how it works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <!DOCTYPE html> <html> <head> <title>Prevent the submit form on enter key except the textarea using jQuery - Clue Mediator</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>Prevent the submit form on enter key except the textarea using jQuery - Clue Mediator</h1> <form method="POST"> <div> <strong>Name:</strong> <input type="text" name="name" placeholder="Name"> </div> <div> <strong>Address:</strong> <textarea></textarea> </div> <button type="submit">Submit</button> </form> <script> $(document).ready(function () { $(window).keydown(function (event) { if ((event.keyCode == 13) && ($(event.target)[0] != $("textarea")[0])) { event.preventDefault(); return false; } }); }); </script> </body> </html> |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂