Search code examples
javascriptkeypressevent-listener

Prevent keypress events from firing in password fields


I am working on a script to capture all key presses in a given HTML page.

Right now I have a basic working script

document.onkeypress = function(event){
    var evtobj=window.event? event : e;
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
        console.log("'Alt', 'Ctrl', or 'Shift' key pressed");
    console.log(String.fromCharCode(evtobj.keyCode));
}

Now, I want to prevent this function from firing in case the event fired on a password field.

Even though the event fires how should I go on to identify that the element is an input box and type is password.

I am guessing it should be done using event.target.


Solution

  • You can also do by checking the type of the input with event.target.type this will return the type the input.

    <input type="password">
    document.onkeypress = function(event){
      if(event.target.type != 'password'){
        var evtobj=window.event? event : e;
        if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
            console.log("'Alt', 'Ctrl', or 'Shift' key pressed");
        console.log(String.fromCharCode(evtobj.keyCode));
      }
    }