Reputation: 449
I found a post on SO that was actually posted yesterday (I cannot find it now) that says my code below should work, but it does not -- the 'handleRtnKey(e)' function below is never called - why?
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// my javascript function -- by the way, I will not be using jquery.
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
None of the alerts fire.
I found a SO post from yesterday that had this near exact code (without my alerts) that claimed to work fine (sorry I cannot re-find that SO post).
I need to use straight javascript (not jquery) to get the key code of the keyup event in my input text box -- that's all I need to do, and if it is the Return key, then I'll take some action, but for now I cannot get the above code to fire that handleRtnKey() function -- why?
EDIT
Damon introduced me to the keyword 'event' and the above code now works fine -- I simply renamed the argument in the html code from 'e' to 'event' and the javascript handler now works fine -- here is the only modification to the code above I had to make:
// OLD
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// NEW
<input type="text" id="zer" onkeyup="handleRtnKey(event)"/>
NOTE: the javascript function handleRtnKey(e) is unchanged, there was no reason for my to change that function's signature, it looks like below and works fine now:
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
THANKS DAMON.
Upvotes: 0
Views: 1928
Reputation: 449
The solution to my problem was as Damon pointed out in his comments above -- I was not aware there was a predefined 'event' keyword and when I used 'event' instead of 'e' in my code above, it worked fine.
Upvotes: 0
Reputation: 17218
you don't need argument at all, just use event
:
function handleRtnKey() {
event = event || window.event; // for cross-browsing
alert(event); // or do whatever you want with it
};
Upvotes: 1
Reputation: 63
The problem is that you call the method with parameter which you don't have. e is not declared. If you remove it it will work. This code worked for me:
<input type="text" id="zer"/>
<script>
window.onload = function () {
document.getElementById("zer").onkeyup = function(event) {
if (event.keyCode == 13) {
alert("Just entered handleRtnKey()");
}
};
};
</script>
Upvotes: 0