Yehuda Zadik
Yehuda Zadik

Reputation: 129

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.charCode) {
         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>

Upvotes: 0

Views: 2838

Answers (2)

Tim Down
Tim Down

Reputation: 324567

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:

Here's a live example for your requirement: http://www.jsfiddle.net/timdown/NAC77/

Upvotes: 1

Secko
Secko

Reputation: 7716

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

Upvotes: 0

Related Questions