0

The code below is supposed to click a button when the Enter key is pressed and empty another textbox if any other key is clicked.

I'm unable to check the keycode as keycode is always undefined.

$('#txtSearch').keyup(function (e) {
    if (e.keycode != 13)
        $('#txtId').val("");
    else
        $('#BtnGo').click();
})
tforgione
  • 1,232
  • 15
  • 28
user3340627
  • 2,823
  • 4
  • 32
  • 75

2 Answers2

1

In Firefox, the keyCode property does not work on the onkeypress event (will only return 0). For a cross-browser solution, use the which property together with keyCode, e.g:

var x = event.which || event.keyCode;  // Use either which or keyCode, depending on browser support

So use following code

$('#txtSearch').keyup(function (event) {
    var x = event.which || event.keyCode;  // Use either which or keyCode, depending on browser support

        if (x!= 13)
            $('#txtId').val("");
        else
            $('#BtnGo').click();
    })

http://www.w3schools.com/jsref/event_key_keycode.asp

Swarnendu Paul
  • 3,937
  • 3
  • 26
  • 54
1

Better way to do this

$('#txtSearch').keyup(function (e) {
    var code = e.keyCode || e.which;
    if(code != 13)
        $('#txtId').val("");

   else
        $('#BtnGo').click();
})
Parth Trivedi
  • 3,774
  • 1
  • 20
  • 38