简体   繁体   中英

How to call the onclick function after pressing Enter

我正在制作聊天网络应用程序,发送消息, input type="text"input type="button" ,使用JavaScript中的函数,我设法通过添加onclick="sendMessage()"来解决它onclick="sendMessage()"作为input button的属性,但我需要点击它,但我希望它像任何聊天信使或应用程序一样工作,客户端写下来并点击ENTER键,如果我使用<form onsubmit="sendMessage()"> ,这可能会有效<form onsubmit="sendMessage()">input type="submit"但页面将刷新,我该怎么做?

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

这可以防止向服务器发送请求的默认操作。

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 (ie 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>

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();"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM