5

I am making a chat web application, to send a message, there's an input type="text" and an input type="button", using a function in JavaScript, I managed to work it out 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 apps, the client writes something down and hits ENTER key, this could work if I used a <form onsubmit="sendMessage()"> and input type="submit" but then the page will refresh, How can I do this?

Ali Bassam
  • 9,691
  • 23
  • 67
  • 117

4 Answers4

4
 <form onsubmit="sendMessage();return false">

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

Snowball
  • 11,102
  • 3
  • 34
  • 51
3

This in-case you want also diable the enter button from Posting to 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();"/>
Stephen Ngethe
  • 1,034
  • 13
  • 24
2

You'll have to hook into the onkeypress/up/down events for the textbox. This should get you started: Enter key press event in JavaScript

Community
  • 1
  • 1
2

Use onkeydown() (or keyPress or keyUp, depending on semantics) instead of on click - this will get you an event with the event.keyCode you want - 13 - and you can easily submit using an AJAX request (i.e. XMLHttpRequest)

Simple Code: - raw Javascript, Don't need JQuery:

<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>
Technologeeks
  • 1,098
  • 8
  • 7