Search code examples
javascriptdom-eventskeyboard-events

How to change input/textarea value with custom keyboard event and keyCode?


I would like to populate a textarea by triggering keyboard events, such as keydown (I'm doing this for a test case).

I have added a snippet (below) to show the code I'm using to create and trigger the event. The event fires, but the textarea never receives the value of keyCode which is the letter A.

What do I need to do to see the letter in the textarea? I'm currently running the snippet in the Chrome console but it should also work in IE9.

var t = document.getElementById('foo');

// Event creation
var event = document.createEvent('HTMLEvents');
event.initEvent('keydown', true, true);
event.keyCode = 65;
event.which = 65;

// Listener for demo purpose
t.addEventListener('keydown', function (e) {
  document.getElementById('fired').value = e.type + ' fired';
});

// Event trigger
t.dispatchEvent(event);
<textarea id="foo"></textarea>

<br>
<input id="fired" value="">


Solution

  • The keydown event is fired when a key is pressed down but it's not the responsible for write the data in the DOM elements.

    The thing is; If the user writes on the <textarea> first the character is added to elements value and then the keyDownevent is triggered. However in your case you're directly triggering the event so the first step which is adding the character to the value for <textarea> is not happening.

    You have two options, do it in the browser way write the value and then dispatch the event

    t.value = t.value + String.fromCharCode(e.keyCode);
    t.addEventListener('keydown', function (e) {
      document.getElementById('fired').value = e.type + ' fired';
    });
    

    Or also you can write the value of the <textarea> on the keyDown event:

    // Listener for demo purpose
    t.addEventListener('keydown', function (e) {
      t.value = t.value + String.fromCharCode(e.keyCode);
      document.getElementById('fired').value = e.type + ' fired';
    });
    

    however if you want to use this second approach for user interaction it's a nonsense because in the case that the users inputs the data, the data will be write it twice (one for the user input and the another one in the event).

    Hope this helps,