JQuery Prevent Submit Form on Enter Key Except Textarea Example

By Hardik Savani November 5, 2023 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....

Shares