I try to hook a character from javascript keydown event
I would like to hook a character typed in an input text field and type '1' in the field in case 'a' was pressed.
Here is the code:
<html>
<body>
<script type="text/javascript">
function translate_code(charCode) {
switch (charCode) {
case 65: //
return '1' ;
case 97:
return '9';
}
}
function noEnglish(event) {
if (event.开发者_StackOverflowcharCode) {
var charCode = event.charCode;
} else {
var charCode = event.keyCode;
}
if (65 <= charCode && charCode <= 90) {
document.getelementbyid("my_name").value += translate_code(charCode) ;
event.returnValue = false ;
}
}
</script>
<form>
<input type="text" name="my_name" id="my_name" onkeydown="noEnglish(event)" />
</form>
</body>
</html>
First, you cannot reliably do what you want with the keydown
event, which is concerned only with the physical key pressed and not the character corresponding with that key. The event you need is keypress
.
I've answered similar questions here before:
- Can I conditionally change the character entered into an input on keypress?
- Changing the keypress
Here's a live example for your requirement: http://www.jsfiddle.net/timdown/NAC77/
Well first of all, if you want the 'a' character and not 'A' you'll have to go from the ASCII character 97 until 123 to get the lower case letters. You'll probably want them all so - 65 until 90 and 97 until 123.
if((charCode >= 65 || charCode <= 90) && (charCode >= 97 || charCode <= 123))
精彩评论