event.keyCode not working in Firefox

不打扰是莪最后的温柔 提交于 2019-11-28 10:16:29

event.keycode was not supported by Firefox. Use event.which for firefox.

function checkKey(evt) {
  var keyID = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
  alert(keyID);
}

I was working on a project, when I faced the same issue. I did some RND and find out these 2-things;

  1. e.keyCode works fine with onkeydown() function, no matter the browser is Chrome or Firefox.

Here is good practices for both Chrome & Firefox.

// HTML (Note onkeydown() function here)
<input id="anyId" onkeydown="return myFunction(event)" type="text" />

// JavaScript for it
function myFunction(e) {
    var asciiValue = e.keyCode ;
    alert ("ASCII Value: " + asciiValue );   // ASCII of pressed key
    if(asciiValue >0){
       return true;
    }
    else{
       return false;
    }
}
  1. But if we use onkeypress() function in Firefox, then e.keyCode will not work. For this purpose, adopt var asciiValue= e.keyCode || e.charCode.
// HTML (Note onkeypress() function here)
<input id="anyId" onkeypress="return myFunction(event)" type="text" />

// JavaScript for it
function myFunction(e) {
    var asciiValue = e.keyCode || e.charCode ;   // It'll handle both Chrome & Firefox
    alert ("Ascii Value: " + asciiValue);    // ASCII of pressed key
    if(asciiValue>0){
       return true;
    }
    else{
       return false;
    }
}

function key_fir(e) { e = e || window.event || {}; var charCode = e.charCode || e.keyCode || e.which; if (charCode == 13) {

               //write your code here Like  $("#log_sub").click();
          }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!