5

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

11

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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.

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;   
}
MrCode
  • 63,975
  • 10
  • 90
  • 112