Ricardo Binns
Ricardo Binns

Reputation: 3246

Key event not firing

My Javascript:

$("#test").keypress(function(e){
       if (document.all){ var evt = event.keyCode; }
       else if(e.which) { var evt = e.which;       }           
       else             { var evt = e.charCode;    }

       if (evt == 13){ // with any other key, the alert dos not fire
            alert(evt);
       }
       return true;
});

Jsfiddle demo

The keycode 13 Enter fires the alert, but any other dosent.

Can any one tell me why?

I need to verify if the 13 or 9 tab was fired.

Thanks.

Upvotes: 0

Views: 257

Answers (2)

hunter
hunter

Reputation: 63522

Use keydown rather than keypress

$('#test').live('keydown', function(e) { 
    var k = e.keyCode || e.which; 

    if (k == 9 || k == 13) { 
        e.preventDefault();
        alert(k);
    } 
});

working: http://jsfiddle.net/hunter/cDVek/15/

Upvotes: 2

defvol
defvol

Reputation: 15470

add a conditional clause to check for evt == 9:

if (evt == 13) { 
   alert(evt); 
} else if (evt == 9) { 
   alert(evt);
}

Upvotes: 0

Related Questions