Javascript: how to check an undefined property

I have the codes below.

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

in IE8, this is occus erros: 'which' is null or not an object

How to solve this problem.

+3
source share
3 answers

The problem is that it eis undefined in IE, because the event object is not passed as an argument to the event handler. You need a property window.event:

elem.onkeypress=function(e) {
  e = e || window.event;
  var charCode = e.which || e.keyCode;
  if (charCode == 13) {
    //dosomething
  }
};
+5
source

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

+1
source

use typeof:

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

0
source

Source: https://habr.com/ru/post/1770687/


All Articles