How to trigger button press from ENTER Key in HTML

491 views Asked by At

I'm making a Chatroom App and want the user to be able to type a message and hit enter when they send it. Currently it only sends when I press the "SEND" button with the mouse. How do I get the message to send when they press the enter key? I basically want to trigger sendMessage() both when they click the button with their mouse, or they just press enter.

I tried using the onkeypress but it is not working

<div class="inputs">
        <input class="msg-input" type="text" rows="3" placeholder="Message" name="message" id="message"/>
        <button type = "button" name="send" id="send-btn" onkeypress="sendMessage()" onClick="sendMessage()">
            Send
        </button>
    </div>`
1

There are 1 answers

0
mohammed alani On

check this link: https://codepen.io/wmizxqve/pen/RwYByxM i have added every thing there.

I think you should go with Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <div class="inputs">
            <input class="msg-input" type="text" rows="3" placeholder="Message" name="message" id="message"/>
            <button type = "button" name="send" id="send-btn" onkeypress="sendMessage()" onClick="sendMessage()">
                Send
            </button>
        </div>

and javascript

$(document).ready(function() {

  $('.msg-input').keydown(function(event) {
    // enter has keyCode = 13, change it if you want to use another button
    if (event.keyCode == 13) {
      sendMessage() //call sendMessage Function;
    }
  });

});