开发者

JavaScript execute function after pressing Enter

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


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


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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜