Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect Enter key in Firefox?

I am trying to detect Enter Key. Here is my code.

HTML

<input name="txtTest"  type="text" id="txtTest" onkeyup="CheckKey()"/>

Javascript

function CheckKey()
{
    var e = window.event;
    var code = e.keyCode ? e.keyCode : e.which;
    if(code === 13)
    {
      alert("You press Enter key.");
    }            
}

This code is working in other browsers but not in Firefox Why? Here is jsFiddle

Please provide answers using javascript only.

like image 653
user1390378 Avatar asked Apr 03 '13 21:04

user1390378


2 Answers

I believe you have to pass the event object to the handler:

<input name="txtTest"  type="text" id="txtTest" onkeyup="CheckKey(event)"/>
<!--                                            passes event object ^   -->
function CheckKey(e) //receives event object as parameter
{
   var code = e.keyCode ? e.keyCode : e.which;
   if(code === 13)
   {
       alert("You press Enter key.");
   }
}

Fiddle

like image 168
Fabrício Matté Avatar answered Sep 21 '22 21:09

Fabrício Matté


You should separate JavaScript code from HTML.

Try something like this - key should work on all browsers:

<input type="text" id="txtTest" onkeyup="CheckKey(e)"/>

function CheckKey(e) {
   var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
   if(key === 13)
   {
       alert("You press Enter key.");
   }
}

Or as suggested with jQuery (separated JavaScript code from HTML) - use event.which:

   <!--HTML file e.g. index.html-->
   <input type="text" id="txtTest" />

    //JavaScript file e.g. script.js - you have to include that script in your HTML file
    $(function(){
      $('#txtTest').on('keyup', function(e){
          if(e.which === 13)
          {
            alert("You press Enter key.");
          }
      });
    });
like image 23
kayz1 Avatar answered Sep 22 '22 21:09

kayz1