JQuery Prevent Submit Form on Enter Key Except Textarea Example
In this post, i will show you how to prevent form submitting on enter key with except textarea using javascript code. You can simply do this on your php, laravel, codeigniter, asp.ent etc project.
In somecases, we require to disable form submit on press enter key on text box that way user must need to press submit button. We can do it simply but if we have to also textarea on that form that it can be cause issue because textarea should accept enter key and goes new line. However, we can also solve this issue by jquery code. So first let's see bellow few lines code for prevent form submit on enter.
JQuery Code:
$(document).ready(function() {
$(window).keydown(function(event){
if((event.keyCode == 13) && ($(event.target)[0]!=$("textarea")[0])) {
event.preventDefault();
return false;
}
});
});
As above, you can see simply we can use in your jquery. I also added full example of this code. So if you don't know how it should work then you can see bellow full example.
index.html
<!DOCTYPE html>
<html>
<head>
<title>JQuery prevent to enter to submit except Textarea</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<form method="POST">
<strong>Name:</strong>
<input type="text" name="name" placeholder="Name">
<strong>Details:</strong>
<textarea></textarea>
<button type="submit">Submit</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
$(window).keydown(function(event){
if((event.keyCode == 13) && ($(event.target)[0]!=$("textarea")[0])) {
event.preventDefault();
return false;
}
});
});
</script>
</body>
</html>
I hope it can help you....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- JQuery - How to Push Specific Key and Value in Array?
- PHP JQuery Ajax Image Upload Example Tutorial
- PHP Ajax Dependent Dropdown List Example
- JQuery Animated Typing Effect using Typed JS Example
- How to Add Lazy Loading Image using JQuery?
- How to Remove Comma from String in JQuery?
- JQuery Tooltip Example using JQuery UI Plugin
- JQuery Bootbox Modal Dialog Prompt Example
- File Upload with Progress Bar using jQuery Ajax and PHP Example
- How to Allow Only One Checkbox Checked at a Time in JQuery?
- How to Check Undefined, Empty and Null in JQuery?
- How to Convert Line Breaks to br in jQuery ?
- How to Check Object is Empty or Not in JQuery?
- Autocomplete with Images and Custom HTML Code in Jquery UI?