I want to submit form as soon as I hit enter in the text area, this was working fine with input type text but, I don't know how to do it with text area. I have to use text area as I want text input to be expandable, how can I make it work? Thanks
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="sendMessage(newMessageContent)">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName " " lastName}}
<textarea id="typeMessageBox" placeholder="Write here and hit enter to send..." type="text submit" class="form-control-lg form-control" ng-model="newMessageContent"></textarea>
</form>
</div>
CodePudding user response:
You can use the following jQuery code to submit your form when hitting Enter in your textarea:
$("#typeMessageBox").keypress(function (e) {
if (e.which === 13 && !e.shiftKey) {
e.preventDefault();
$(this).closest("form").submit();
}
});
That said, it may not be a good idea. If you want an expandable field, that surely is because you'll have several lines of text, therefore almost certainly a line break.
I would highly encourage you to add a helptext stating that you WILL submit the form when entering Enter, as your users would be very surprised by this behavior.
Even better: don't try to change native behaviors. A textarea is working like this for a good reason, and everybody is used to it. Changing its behavior may seem a good idea to you, but you'll probably loose your users.
CodePudding user response:
You can use ng-keypress and then check if keypress is equal enter then call to submit form function
On your textarea should be
<textarea ng-keypress="getkeys($event)" ng-model="newMessageContent"></textarea>
Then your angular code shold be
$scope.getkeys = function (event) {
if(event.keyCode == 13){
$scope.sendMessage( $scope.newMessageContent );
}
}