How to prevent submit form on enter key except textarea in JQuery?

By Hardik Savani | June 6, 2017 | | 58549 Viewer | Category : PHP Javascript HTML jQuery


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
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: