Search code examples
javascriptkeyboarddom-eventscontenteditable

Javascript input change


Is it possible to change the input value of the keyboard?

For example:

You press the a key on your keyboard but b will be typed into the input element, instead of a.

You type abc but in the input element will be def.

I tried to capture the keydown event and then fire a keydown event with CustomEvent / Event, but It doesn't work for me. The event capturing is fine but when I create an other keydown event with the new charCode or keyCode the 'new' character won't be typed into the input.

So, is it possible to write something into an input element to the position of the caret, without using value property or any other methods which handle or modify the whole content of the input. So just insert or paste a letter.

JS

function keydown(e) {
    e.preventDefault();

    var event = new Event('keydown');
    event.charCode = 65;
    element.dispatchEvent(event);
}

HTML

<input type="text" onkeydown="keydown(event)">

Probably, this is not possible in this way but I haven't any other idea so far...


Solution

  • I found another way to do this with document.execCommand():

    document.querySelector("input")
    .addEventListener("keypress", function (event) {
      event.preventDefault();
      document.execCommand('insertText', false, 'b');
    })
    <input>