Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
Arun Chandran C Avatar asked Jun 12 '13 06:06

Arun Chandran C


2 Answers

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

like image 96
Arun P Johny Avatar answered Sep 30 '22 02:09

Arun P Johny


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.

Fiddle

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;   
}
like image 36
MrCode Avatar answered Sep 30 '22 04:09

MrCode