Search code examples
javascriptjquerykeypress

Implementing key press with JS and jQuery


I want on a key press an alert box will get displayed. It is done. But the problem is I have a textbox inside the page and when I am trying typing inside the textbox then also the alert box is coming.

$(document).ready(function() {
    $(document).keydown(function(e) {
        if (e.key == "F8") {
            alert('Right key pressed');
        } else {
            alert("Error key pressed")
        }
        e.preventDefault();
    })
});

HTML:

<input type="text" />

Solution

  • Textbox is element of your document so it is good behavior that it raise document's events.

    You should add handler to textbox to stop propagate event to document layer

    $('input').keydown(function (e) {
       e.stopPropagation();
    }