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.
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
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.");
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With