Keyboard Event Handling: onkeypressQuestion: Which character did the user type?
Answer:
To identify the printable character the user has typed, use the keypress event.charCode (supported in most browsers except MSIE, Opera)
keypress event.which (supported in most browsers other than MSIE)
keypress event.keyCode (character code in Internet Explorer)
Unlike
Click here and press any key This example uses the function keypressHandler(e) { var evt = e ? e:event; var chrTyped, chrCode = 0; var sProperties = '' +(evt.keyCode ==null ? '':' keyCode=' +evt.keyCode ) +(evt.charCode==null ? '':' charCode='+evt.charCode) +(evt.which ==null ? '':' which='+evt.which) if (evt.charCode!=null) chrCode = evt.charCode; else if (evt.which!=null) chrCode = evt.which; else if (evt.keyCode!=null) chrCode = evt.keyCode; if (chrCode==0) chrTyped = 'SPECIAL KEY'; else chrTyped = String.fromCharCode(chrCode); document.getElementById('sChrCode').innerHTML = sProperties; document.getElementById('sChrName').innerHTML = ' Character: '+chrTyped.bold(); return true; } //Register the event handlers: document.onkeypress=keypressHandler; See also: |
Copyright © 1999-2012, JavaScripter.net.