1

I wanted to know how its possible to call a javascript function , as soon as one presses the "return(enter" key,just as in chat systems

3 Answers 3

2

The following will do what you want reliably in all major browsers. In IE, you need to get the event object via window.event because it is not passed in as a parameter to the function. Also, using the character code rather than a key code will mean that all enter keys are automatically detected without needing separate detection for each.

For more information on handling key events in JavaScript, I consider http://unixpapa.com/js/key.html the definitive reference.

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    if (charCode == 13) {
        // Insert Enter handling code here
        alert("Enter pressed");
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0
window.onkeypress = function(e)
{
 switch(e.keyCode e.which) //[2]
 {
  case NUMPAD_ENTER_KEY_CODE: //[1]
  case ENTER_KEY_CODE:
   doSomething();
   return false;
  default:
   if (window.console) console.log(e.keyCode e.which); //[2]
   return true;
 }
}

this is then expandable to work for any number of key codes. You can also try the onKeyDown or onKeyUp events.

Remember to replace ENTER_KEY_CODE with the actual key code (32?). This should print out the keyCodes of any keys that are not enter so that you can figure out their keyCodes.

Edit:
[1] I forgot to mention you may want to detect the numpad-enter keycode.
[2] I forgot that onkeypress uses e.which to store the keyCode

3 Comments

table for keyCode webonweboff.com/tips/js/event_key_codes.aspx & more on detecting key stroke quirksmode.org/js/keys.html
apologies, onkeypress uses e.which. I'm used to using normalized events in jQuery. onkeydown uses e.keyCode.
The main problem in IE is that there's no event object passed into the event handler function. You need to use window.event in IE.
-1

Enter any thing in Text box then press Enter to execute

<form onSubmit='alerttest(this); return false'>        
    <input type="text">         
</form>


<script language="javascript">
    function alerttest()
    {
        alert("Executing jolly.exe !!!!");
        // function edited by Inderpreet singh
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.