2

This code is responsible for preventing users from entering non-numeric characters such any any ascii except number [0-9]. Works fine in in IE, but not in Firefox and Chrome. Any help and suggestions are highly appreciated.

Thank you

'oKeyPress': function (e) {
    e = e || window.event;
    var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Shiva
  • 1,379
  • 1
  • 15
  • 32
  • 2
    Note the use of `navigator.appName` to decide which property to use for the key code, [that's not a good way of doing it](http://stackoverflow.com/questions/14573881/why-the-javascript-navigator-appname-returns-netscape-for-safari-firefox-and-ch). – Orbling May 31 '13 at 17:07
  • For how to fix it, see: http://stackoverflow.com/questions/4471582/javascript-keycode-vs-which - the second answer shows how. – Orbling May 31 '13 at 17:08
  • 1
    Though the event name may also be wrong, just noticed the 'oKeyPress' presumably that should be 'onKeyPress'? – Orbling May 31 '13 at 17:10
  • Netscape check, yikes, burn whatever you used to get that reference. `var keyCode = e.keyCode || e.which;` – epascarello May 31 '13 at 17:10
  • @epascarello: There's also `e.charCode`. jQuery has `e.charCode != null ? e.charCode : e.keyCode` where `e.which` isn't already set. – Orbling May 31 '13 at 17:13

3 Answers3

2

Use feature detection; not browser detection:

var charCode = e.charCode || e.keyCode;
svidgen
  • 13,744
  • 4
  • 33
  • 58
1

inside your KeyPress event to get the charcode use this:

return (window.event ? e.keyCode : e.which)
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
0

Thank you guys for your suggestions and feedback; I just found out why it did not work on Firefox and chrome before. The reason it was not working was because I was using something like this code from my Code-behind C# code :

this.txtApsId.Attributes.Add("onkeypress", "return (function(e) {var charCode = (navigator.appName == 'Netscape') ? e.which : e.keyCode; return charCode > 31 && (charCode < 48 || charCode > 57); }(event || window.event))");

Thanks

Shiva
  • 1,379
  • 1
  • 15
  • 32