I have a textarea field and it's data will be submitted using java script and ajax by pressing enter key, the problem is that when the user press the enter key first it will create a new line then the textarea will be submitted, and i don't want it to create a new line.
Please help!
I have a textarea field and it's data will be submitted using java script and ajax by pressing enter key, the problem is that when the user press the enter key first it will create a new line then the textarea will be submitted, and i don't want it to create a new line.
Please help!
Share Improve this question asked Jun 27, 2015 at 4:25 Mohammad Samim SamimeeMohammad Samim Samimee 572 silver badges8 bronze badges 1- 1 With jquery, bind the keyup event of the textarea, capture the event object in the first argument. Use this object to cancel event when the pressed key is enter. I believe it s code is 13. jQuery has all the doc for that, SO all the posts for that also. One thing not to do is to cancel the propagation, otherwise you may need to also trigger submit event at that point. – user4466350 Commented Jun 27, 2015 at 4:28
2 Answers
Reset to default 8Just listen to the keydown
event and prevent the default action (which is the linebreak)
$("textarea").on("keydown", function(e) {
if(e.which === 13) { // enter key
e.preventDefault(); // prevents linebreak
// here you could add your submit call
return false;
}
});
You can use jQuery to determine whether the textarea is active:
$("#foo").is(":focus") // expression is true only when it is active
So your code should look something like this:
if (<enter key pressed> and !($("#foo").is(":focus")))
<submit with JavaScript and Ajax>