views:

29

answers:

2

Can anybody tell me why is this not working?

  <input name ="txtChat" id ="txtChat" onkeydown ="isEnterPressed();"  type="text" style="width:720px;"/>

This is my javascript function :-

 function isEnterPressed(event){
                alert(event);

            }

On alert i always gets undefined :(

Thanks in advance :)

+2  A: 

There is no built-in event type that is fired when the enter key is pressed, you need to check that in the Event object that is passed to the handler.

HTML:

<input name ="txtChat" id ="txtChat" onkeyup="onKeyPressed(event)"  type="text" style="width:720px;"/>

JavaScript:

function onKeyPressed(ev) {
   var e = ev || event;
   if(e.keyCode == 13) {
      //Enter was pressed
      return false; //prevents form from being submitted.
   }
}
Jacob Relkin
Thanks Jacob Relkin, now its working and enter key is captured. But i am facing another problem now. The page reloads as soon as i press enter key :(. Any idea, why is this happening? I have a `form` tag and this is causing problem. As soon as i remove it, it works fine. How do i get rid of this problem?
Ankit Rathod
Yes, this is because the `form` is being submitted by default. I'll edit my answer.
Jacob Relkin
Thanks Jacob :)
Ankit Rathod
Great Jacob except that `return false` should be inside `e.keyCode` ;).
Ankit Rathod
@Nitesh, you're right.
Jacob Relkin
A: 

A very simple inline check is:

<input name ="txtChat" id ="txtChat" onkeydown ="alert(event.keyCode == 13);"  type="text" style="width:720px;"/>

which outputs true if enter is pressed.

digitalFresh