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?
<form onsubmit="sendMessage();return false">
That prevents the default action of sending a request to the server.
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();"/>
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With