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 ?
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!