0

I am trying to make a press enter to send data using jquery but my code is not working. Anyone can tell me what i am missing here ?

<textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea>

JS

function SendMessage() { 
       $.ajax({
        type: "POST",
        url: "/ajax/reply",
        data: dataString,
        cache: false,
        success: function(html) {
            $('.messages-body').append(html);
        }
      });
     }

   $('#replyChat').bind('keydown', function(e) {
      if(e.keyCode==13) {
        SendMessage();
    }
  });
  $('body').on("click",".reply-btn",function() {
     SendMessage();
 });

Click function is working fine just keydown doesn't work here.

AlwaysStudent
  • 1,354
  • 18
  • 49

1 Answers1

1

Use event delegation for the dynamically generated element, although use event.which property which is suggested by jQuery.

function SendMessage() {
  console.log('hi');
  // replace with your ajax code
}

$('body').on('keydown', '#replyChat', function(e) {
  if (e.which == 13) {
    SendMessage();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="reply" class="reply" id="replyChat" placeholder="Write your message"></textarea>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188