简体   繁体   中英

jQuery javascript keypress function not working on IE8

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();
}
}

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;

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM