How to prevent the submit form on enter key except the textarea using jQuery
📅February 11, 2022
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
- How to search an array in JavaScript
- How to get all cookies using JavaScript
- Detect a mobile device using JavaScript
- 7 JavaScript One-Liners that you should know
- How to get yesterday’s, today’s, and tomorrow’s date using JavaScript
Let’s check the following jQuery code to prevent a form on enter.
$(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.
index.html
<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>
<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>
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂