Search code examples
javascriptjqueryeventskeypress

Changing the charCode of the key pressed


In following example I am attempting to change the charCode of the key pressed but it does not change. When I press "a" I want it to type "b". What am I doing wrong?

$("#target").keypress(function(event) {
     if ( event.which == 97 ) {
         //alert('pressed a');
         //event.preventDefault();
         event.keyCode = 98;
         event.charCode = 98;
         event.which = 98;
     }
});

Solution

  • You can't override the keycode in the event object...

    Look at this snippet:

    $('#target').keypress(function(e){
        if (e.which == 97)
            this.value = this.value + String.fromCharCode(98)
        else
            this.value = this.value + String.fromCharCode(e.which)
    
        ....
    
        return false;
    })