How to call the onclick function after pressing Enter

I am making a chat web application to send a message, there input type="text" and input type="button" , using a function in JavaScript, I managed to process it by adding onclick="sendMessage()" as an attribute for the input button , but I need to click on it, but I want it to work like any chat messengers or applications, the client would record something and press the ENTER key, this might work if I used <form onsubmit="sendMessage()"> and input type="submit" , but then the page will refresh, how can I do this?

+4
source share
4 answers
  <form onsubmit="sendMessage();return false"> 

This prevents the default action of sending a request to the server.

+4
source

You need to connect to the onkeypress / up / down events for the text field. This should help you get started: Enter a keystroke event in JavaScript

+2
source

Use onkeydown () (or keyPress or keyUp, depending on the semantics), and not on click - this will give you the event with event.keyCode you want - 13, and you can easily send an AJAX request (e.g. XMLHttpRequest)

Simple code: - raw Javascript, no jQuery needed:

 <html> <script> function keyPress(e) { if (!e) e = window.event; // needed for cross browser compatibility alert(e.keyCode); // You want 13 here , so // if (e.keyCode == 13) // etc.. // return true; or false, if you want to cancel event } </script> <body> <input type="text" onkeydown="keyPress()" size="20"/>xx </body> </html> 
+2
source

In this case, you can also enter the disable enter button from Posting to the server and execute the Js script.

 <input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13) {document.getElementById('btnSearch').click(); return false;}"/> <input type="button" id="btnSearch" value="Search" onclick="doSomething();"/> 
+1
source

All Articles