3

I have codes below.

elem.onkeypress=function(e){
 if( (e.which===undefined?e.keyCode:e.which)==13 ){
   //dosomething
  }
}

at IE8, it occus erros: 'which' is null or not an object

how to fix this problem.

guilin 桂林
  • 16,458
  • 26
  • 90
  • 143
  • 1
    possible duplicate of [Best way to check for "undefined" in javascript](http://stackoverflow.com/questions/3390396/best-way-to-check-for-undefined-in-javascript) and others... – Felix Kling Oct 21 '10 at 08:48
  • a little bit diffrence is this one is check wheather a property of a Object is undefined, not a variable. – guilin 桂林 Oct 21 '10 at 09:12
  • The problem's nothing to do with the `undefined` check of the `which` property. The problem is that `e` is undefined. – Tim Down Oct 21 '10 at 09:14

3 Answers3

5

The problem is that e is undefined in IE because no event object is passed as a parameter to the event handler. You need the window.event property:

elem.onkeypress=function(e) {
  e = e || window.event;
  var charCode = e.which || e.keyCode;
  if (charCode == 13) {
    //dosomething
  }
};
Tim Down
  • 306,503
  • 71
  • 443
  • 520
1

One option is to go with (e.hasOwnProperty('which') ? ...

Saul
  • 17,666
  • 8
  • 59
  • 87
0

use typeof:

if (typeof e.which == 'undefined' ? e.keyCode : e.which) == 13)

Dan Grossman
  • 50,627
  • 10
  • 109
  • 97