Skip to content
Amal Hashim
All posts
Snippet

jQuery KeyDown Event

A generic JavaScript function to capture a key press and run logic, such as clearing a field on backspace.

1 min read#ASP.NET#JavaScript#jQuery

Sometimes you need to capture the KeyDown event and run some business logic. This generic function handles the key code differences between browsers.

js
function CheckKey(e) {
    var keynum;
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    if (keynum == 8) {
       //Example: If backspace clear id
       $('#employeeid').val('');
    }
}

Example

Attach the function to the input's onkeydown attribute. Pressing backspace in the box clears the employeeid field.

html
<input id="txtEmployee" onkeydown="CheckKey(event);" />