1

I've the following jquery function which avoid typing "1" in the input text:

<input id="myId" style="width:50%;" value="0" type="text">​

$("#myId").keypress(function(e) {
   var x=e.charCode;
   if (x == '49'){
       e.preventDefault();
   }
});​

This is the jsfiddle

which is not working on IE8. Where is my error? Thanks in advance!

EDIT JAVASCRIPT VERSION

<input id="myId" style="width:50%;" value="0" type="text"  onkeypress="javascript:checkNumber(event);"/>

function checkNumber(event) {
var x=e.which;
if (x == 49){
    event.preventDefault();
}
}
Fseee
  • 2,476
  • 9
  • 40
  • 63

3 Answers3

3

charCode is not cross-browser, you can use jQuery which property:

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

var x = e.which;

If you don't use jQuery, you can code:

var x = e.charCode || e.keyCode;
Ram
  • 143,282
  • 16
  • 168
  • 197
  • According to [this well written answer](http://stackoverflow.com/a/3051784/1243160), "which is a property of Event objects. It is defined for key-related and mouse-related events in most browsers, but in both cases is not defined in IE (prior to version 9)." – crowjonah Nov 21 '12 at 14:39
  • Apologies: I realize that jQuery `which` addresses this. [This answer](http://stackoverflow.com/a/2412501/1243160) suggests passing the `event` by a different name so as not to conflict with IE's event object. – crowjonah Nov 21 '12 at 14:44
  • @crowjonah Yes, jQuery normalizes that. – Ram Nov 21 '12 at 14:49
  • @undefined that's working but how about javascript?? See my edit please – Fseee Nov 21 '12 at 15:14
  • @undefined it says "method or property not supported" referring to event.preventDefault(); – Fseee Nov 21 '12 at 15:23
  • @Franky IE8 doesn't support preventDefault method check this question http://stackoverflow.com/questions/1000597/event-preventdefault-function-not-working-in-ie – Ram Nov 21 '12 at 16:02
0

See this answer to a similar question. Try keydown instead of keypress and keyCode instead of charCode:

$("#myId").keydown(function(e) {
   var x=e.keyCode;
   if (x == '49'){
      e.preventDefault();
   }
});​

the jQuery documentation for keypress lists a few good reasons to use keydown instead, not the least of which is that it only fires once for a press and hold, and keypress reports the character, not the key (which is problematic when dealing with things like capslock.)

Community
  • 1
  • 1
crowjonah
  • 2,858
  • 1
  • 23
  • 27
0

Use e.which instead, since e.charCode isn't supported on all browsers.

Also, you might consider using .keyup() event instead of .keypress()

Abhilash
  • 1,610
  • 9
  • 19