473,226 Members | 1,319 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,226 software developers and data experts.

Multiple meanings for keyCode or which value

Frinavale
9,735 Expert Mod 8TB
I have a some text inputs that expect numbers as input. I have written a function that returns false if any key other than one that represents a number is pressed. I call the function during the onkeypress event and this prevents the user from entering anything that is not a number.

Expand|Select|Wrap|Line Numbers
  1. function NumbersOnlyFilter(e){
  2.     var keynum;
  3.     if (window.event || e.keyCode) {
  4.         keynum = e.keyCode;
  5.     }else if (e.which) {
  6.         keynum = e.which;
  7.     }
  8.  
  9.     if (keynum >= 48 && keynum <= 57) {  
  10.         //characters 0-9
  11.         return true;
  12.    }
  13.    //returning true if it's the enter key, backspace key, or a movement key; otherwise false.
  14.    return IsMovementOrEnterKey(keynum);
  15. }
In order to let the user move within the text input field I have also allowed the user to press backspace, enter, left, right, up, down, tab, home and end. The problem is that the keyCode/which value for these sometimes match characters as well!

Expand|Select|Wrap|Line Numbers
  1. function IsMovementOrEnterKey(keynum) {
  2.     if (keynum == 8 || keynum == 9 || keynum == 13 || keynum == 35 || keynum == 36 || keynum == 37 || keynum == 46 || keynum==39) {
  3.         //Backspace: 8
  4.         //Tab: 9
  5.         //Enter: 13
  6.         //End: 35  (also #)
  7.         //Home: 36 (also $)
  8.         //Delete: 46 (also .)
  9.         //Left Arrow: 37 (also %)
  10.         //Right Arrow: 39 (also ')
  11.         return true;
  12.     }
  13.     return false;
  14. }
How can I tell if it's a movement key pressed, or if it's a character?

Thanks for your time,

-Frinny
Apr 7 '09 #1

✓ answered by Frinavale

After reading this article I think I've found the answer to my question.

The charCode value returns the ASCII of the key pressed; whereas the keyCode property returns the keyboard value for the key pressed. If the key doesn't have an ASCII value then the charCode property returns 0. The charCode property is only available during the onkeypress event.

The only thing is that IE and Opera don't support charCode (it's undefined). I this case I'll have to use the keyCode property. Apparently (when testing this in IE) the onkeypress event isn't fired when special keys (keys with no ASCII value) are pressed.

For example:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <body>
  3.     <script type="text/javascript">
  4.       function NumbersOnlyFilter(e)
  5.       {
  6.         var keynum = ASCIIKeyPressValue(e);
  7.  
  8.         if (keynum >= 48 && keynum <= 57) {  
  9.             //characters 0-9
  10.             return true;
  11.        }
  12.        //returning true if it's the enter key or a movement key; otherwise false.
  13.        return IsMovementOrEnterKey(keynum);
  14.       }
  15.  
  16.       function ASCIIKeyPressValue(e) {
  17.         var keynum;
  18.         if (e.charCode != null) {
  19.             keynum = e.charCode;
  20.         } else if (e.keyCode != null) {
  21.             keynum = e.keyCode;
  22.         } else if (e.which != null) {
  23.             keynum = e.which;
  24.         }
  25.         return keynum;
  26.       }
  27.  
  28.       function IsMovementOrEnterKey(keynum) {
  29.         if (keynum == 0 || keynum == 8 || keynum == 9 || keynum == 13) {
  30.             //Backspace: 8
  31.             //Tab: 9
  32.             //Enter: 13
  33.             return true;
  34.         }
  35.         return false;
  36.       }
  37.     </script>
  38.  
  39.     <input type="text" onkeypress="return NumbersOnlyFilter(event);" />
  40.  
  41.   </body>
  42. </html>

5 5842
Frinavale
9,735 Expert Mod 8TB
After reading this article I think I've found the answer to my question.

The charCode value returns the ASCII of the key pressed; whereas the keyCode property returns the keyboard value for the key pressed. If the key doesn't have an ASCII value then the charCode property returns 0. The charCode property is only available during the onkeypress event.

The only thing is that IE and Opera don't support charCode (it's undefined). I this case I'll have to use the keyCode property. Apparently (when testing this in IE) the onkeypress event isn't fired when special keys (keys with no ASCII value) are pressed.

For example:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <body>
  3.     <script type="text/javascript">
  4.       function NumbersOnlyFilter(e)
  5.       {
  6.         var keynum = ASCIIKeyPressValue(e);
  7.  
  8.         if (keynum >= 48 && keynum <= 57) {  
  9.             //characters 0-9
  10.             return true;
  11.        }
  12.        //returning true if it's the enter key or a movement key; otherwise false.
  13.        return IsMovementOrEnterKey(keynum);
  14.       }
  15.  
  16.       function ASCIIKeyPressValue(e) {
  17.         var keynum;
  18.         if (e.charCode != null) {
  19.             keynum = e.charCode;
  20.         } else if (e.keyCode != null) {
  21.             keynum = e.keyCode;
  22.         } else if (e.which != null) {
  23.             keynum = e.which;
  24.         }
  25.         return keynum;
  26.       }
  27.  
  28.       function IsMovementOrEnterKey(keynum) {
  29.         if (keynum == 0 || keynum == 8 || keynum == 9 || keynum == 13) {
  30.             //Backspace: 8
  31.             //Tab: 9
  32.             //Enter: 13
  33.             return true;
  34.         }
  35.         return false;
  36.       }
  37.     </script>
  38.  
  39.     <input type="text" onkeypress="return NumbersOnlyFilter(event);" />
  40.  
  41.   </body>
  42. </html>
Apr 7 '09 #2
dmjpro
2,476 2GB
As no standard key event handling supported then why not you using regular expression to check whether an unexpected key pressed or not.
I think you get the text field value on "KeyPress" event then check whether it's valid, if not then replace the unexpected character with "empty string"
Apr 8 '09 #3
Frinavale
9,735 Expert Mod 8TB
Even though I love using Regular Expressions, when you handle the onkeydown, onkeyup, or onkeypress you do not have a string to deal with. You have the value of the key that was pressed (which is a number). At this time, the value has not been entered into the text box, it's simply a number (this is how I'm preventing the value from being entered into the text box). So, Regular Expressions can't help me here.

I solved the problem by handling the "onkeypress" event instead of the "onkeydown" event that I was using originally. During the "onkeypress" event, in some browsers, the "charCode" value is available through the event Object. This value represents the ASCII value of the key that was pressed.

The "keyCode" (that I was using originally) represents the actual button that was pressed (not the ASCII value of it). So, when I used this value special buttons (like the Home key) matched the ASCII values. It was impossible to tell which key was actually being pressed.

The "charCode" value is 0 if a special key is pressed.
And apparently, special keys don't raise the "onkeypress" event in the browsers that don't support "charCode"...so for these cases I use the "keyCode" value instead.

See the example I posted earlier.

:)

-Frinny
Apr 8 '09 #4
Frinavale
9,735 Expert Mod 8TB
Apparently I'm still experiencing problems with this.

Now, however, it's the number pad that is giving me problems.

In Internet Explorer, if numlock is on, then the number-pad returns values ranging from ASCII 96 (representing the number 0) to ASCII 105 (representing the number 9). However, this range also represents represents "a" to "i" and the "`" character.

I can't seem to find a way to check if numlock is on...

Does anyone have any advise on how to get around this issue?

Thanks,

-Frinny
Sep 20 '10 #5
Frinavale
9,735 Expert Mod 8TB
Ok, never mind, apparently I was making the same mistake as before (using onkeydown instead of onkeypress) I just didn't notice it when I posted this question because I had both events calling the method.

*blush*

-Frinny
Sep 20 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Perttu Pulkkinen | last post by:
I have different functions that receive window.event as parameter. Functions are used like this: <input type="text" id="x" onkeypress="return onKeyCurrencyCheck(ev, 'x')" onblur...
6
by: rich_poppleton | last post by:
Help.... I've got a textarea where people type in a description. However for certain reasons we need to stop them typing !$*^ . I have a solution this which works fine in IE: function...
4
by: Thomas Christensen | last post by:
I'm trying to figure out what key the user pressed using a Danish keyboard layout. charCodeAt returns the correct number, but event.keyCode returns a wrong number, when using one of the keys that...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
5
by: WilliamRLinden | last post by:
Hi world! we are pretty new to JavaScript and have been struggling for now 2 days on this problem ... We would appreciate mercy if anyone can give us some. Basically we are trying to simulate...
4
by: jayscott1 | last post by:
What I would like to do is have the user start typing in the last name and as they were typing it would retrieve names from the database and give a drop down like autosuggest in google. That much...
3
by: Paul Gorodyansky | last post by:
Hi, I have function that works via onkeypressed - for example, what to catch when a user presses a punctuation symbol such as '.' So I check keyCode for that - works just fine in Opera 8,...
1
by: Peter Anthony | last post by:
This is a perfect example of how some information slips through the crack in MSDN2. There is NO explanation of what KeyValue is in MSDN2!! Sure, it has a page on it, here it is: ...
3
by: didi86 | last post by:
Please help me to adding multiple row at a time... // Last updated 2006-02-21 <script language="javascript"> function addRowToTable() { var tbl = document.getElementById('tblSample'); ...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.