简体   繁体   中英

How to submit form with enter press in html textarea

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> 

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.

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 );
   }        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM