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,234
  • 15
  • 29
user3340627
  • 3,023
  • 6
  • 35
  • 80

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

Scarecrow
  • 4,057
  • 3
  • 30
  • 56
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,802
  • 1
  • 20
  • 40