user3340627
user3340627

Reputation: 3143

Check on keycode return undefined

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();
})

Upvotes: 0

Views: 137

Answers (2)

Scarecrow
Scarecrow

Reputation: 4137

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

Upvotes: 1

Parth Trivedi
Parth Trivedi

Reputation: 3832

Better way to do this

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

   else
        $('#BtnGo').click();
})

Upvotes: 1

Related Questions