'ReferenceError: event is not defined in mozila firefox [duplicate]
This code is not working for me in Firefox(V21.0) but works in IE(V9,V10) and Chrome (V 27.0.1453.110 m)
Method cal:
<input type="text" id="txt1" class="search-bar-input"
onkeyup="handleKeyPress('btn1');">
Method definition:
function handleKeyPress(searchButtonId) {
if (event.keyCode === 13) {
alert(event.KeyCode);
}
}
Error Message:
ReferenceError: event is not defined
if (event.keyCode === 13) {
Does anyone have any idea to solve the issue?
Solution 1:[1]
Use
<input type="text" id="txt1" class="search-bar-input" onkeyup="handleKeyPress(event, 'btn1');">
Then
function handleKeyPress(event) {
event = event || window.event //For IE
if (event.keyCode === 13) {
alert(event.keyCode);
}
}
Demo: Fiddle
Solution 2:[2]
You could store the btn1 parameter as a data-* attribute and use unobtrusive Javascript to assign the event handler (instead of inline).
Also your line alert(event.KeyCode); is wrong, the K in KeyPress should be lowercase k.
HTML
<input type="text" id="txt1" class="search-bar-input" data-searchButtonId="btn1" />
Javascript:
function handleKeyPress(event) {
if (event.keyCode === 13) {
console.log(event.keyCode + this.getAttribute("data-searchButtonId"));
}
}
window.onload = function(){
document.getElementById("txt1").onkeyup = handleKeyPress;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arun P Johny |
| Solution 2 | MrCode |
