javascripteventskeypresskeyboard-events

Altering the keypress event of certain keys in JavaScript


I am working on a project which shows the character code of each key that is pressed down inside a text box.

My problem is that when certain keys, namely: Shift, Backspace, Space are pressed down, their character codes appear like: 16, 8, 32.

I want these keys to retain their normal behavior when pressed. So that space causes a space in the text box, and backspace deletes the character, and so on...but the rest of the keys to continue outputting their character code.

How can I go about accomplishing this?


Solution

  • You can just check for the keys and handle accordingly. Here's a demo:

    document.getElementById("test-textbox").addEventListener("keypress", function(event) {
        var code = event.keyCode || event.which;
      
        if(code === 16 || code === 8 || code === 32) //check if space, shift, or backspace
            return; //if yes, allow
        
        console.log(code); //if not, log value  
        event.preventDefault(); //prevent entry
    });
    <input type="text" id="test-textbox">

    This will allow the shift, backspace, and space keys to be pressed, but all others will be logged.