Detect printable keys

I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.

I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.

function isCharacterKeyPress(evt) {
    if (typeof evt.which == "undefined") {
        // This is IE, which only fires keypress events for printable keys
        return true;
    } else if (typeof evt.which == "number" && evt.which > 0) {
        // In other browsers except old versions of WebKit, evt.which is
        // only greater than zero if the keypress is a printable key.
        // We need to filter out backspace and ctrl/alt/meta key combinations
        return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
    }
    return false;
}

var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
    evt = evt || window.event;

    if (isCharacterKeyPress(evt)) {
        // Do your stuff here
        alert("Character!");
    }
});

Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.

test.onkeydown = e => {
  let isPrintableKey = e.key.length === 1;
  alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">

Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.

This method is much more reliable simply because unlike event.which, event.key is already standardized.