Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the onclick function after pressing Enter

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?

like image 386
Ali Bassam Avatar asked Aug 23 '12 21:08

Ali Bassam


4 Answers

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

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

like image 165
Snowball Avatar answered Oct 31 '22 16:10

Snowball


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();"/>
like image 37
Stephen Ngethe Avatar answered Oct 31 '22 17:10

Stephen Ngethe


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

like image 2
Michael Evangelist Avatar answered Oct 31 '22 16:10

Michael Evangelist


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>
like image 2
Technologeeks Avatar answered Oct 31 '22 15:10

Technologeeks