March 9, 2013
Send a message when pressing Enter
Question by Sora
Here is my code:
<input type="text" id='MsgToSend" + ToClient + "t" + FromClient + "' onkeypress='ClientOnTyping();' />
where the FromClient
and the ToClient
are dynamically generated.
JavaScript:
function ClientOnTyping() {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
}
Answer by Starx
You need to attach an event listener on the element for keydown
event.
var btn = document.getElementById('MsgToSend');
btn.addEventListerner('keydown', function (e) {
if(e.keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});
On traditional browsers, you can attach the event handler this way.
var btn = document.getElementById('MsgToSend');
btn.onkeydown = function (e) {
e = e || window.event;
var keyCode = e.keyCode || e.which;
if(keyCode==13) {
// i know i should do this but my problem is what is 'e' in my case how can i specify it ?
}
});