Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to check a property is undefined

Tags:

javascript

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.

like image 453
guilin 桂林 Avatar asked Dec 29 '25 12:12

guilin 桂林


2 Answers

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
  }
};
like image 115
Tim Down Avatar answered Jan 01 '26 00:01

Tim Down


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

like image 42
Saul Avatar answered Jan 01 '26 02:01

Saul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!