0

hey i'm making an chat program but I dont know how to assign the "enter" button to a onclick function.

<input id = "SendMessage" onclick="Send()" value = "Send" class = "Button" type = "submit">

thats my code. does someone have an awnser? Have a nice day!

Jordy dev
  • 27
  • 1
  • 7
  • May be https://stackoverflow.com/questions/11365632/how-to-detect-when-the-user-presses-enter-in-an-input-field – Alex77 Mar 29 '22 at 11:27

1 Answers1

0

You need to create a keydown event listener like this:

var input = document.getElementById("input");
input.addEventListener("keydown", event => {
  if (event.keyCode === 13) { //13 is the keycode of ENTER
    Send();
  }
});

function Send(){
  alert(input.value + " - has been sent");
}
<input id = "input" type="text"/>
<input id = "SendMessage" onclick="Send()" value = "Send" class = "Button" type = "submit">
ATP
  • 2,939
  • 4
  • 13
  • 34
  • can you make it so i can just copy paste it in my code? Im new to coding and it's sometimes hard to understand – Jordy dev Mar 28 '22 at 14:41
  • Do i have to put the "var input = document.getElementById("input"); input.addEventListener("keydown", event => { if (event.keyCode === 13) { //13 is the keycode of ENTER Send(); } }); function Send(){ alert(input.value + " - has been sent"); }" in the script.js file? – Jordy dev Mar 28 '22 at 14:51
  • I now got 2 message input's instead of 1? – Jordy dev Mar 28 '22 at 14:53
  • @Jordydev I assumed there is a text input in your code because you want to send on enter press. Since you didn't post your full code including the text box and `Send` function I made them. if you want the enter to be recognized everywhere on the page use `document.addEventListener("keydown", event => { if (event.keyCode === 13) { //13 is the keycode of ENTER Send(); } });` – ATP Mar 28 '22 at 14:55