Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatching a KeyboardEvent fails to produce the character in a textarea

Tags:

javascript

var el = document.getElementById('action');

el.addEventListener('click', function()
{
    var t = document.getElementById('text');
    t.value = 'A should be typed later';
    t.focus();
    t.setSelectionRange(0, 0);

    setTimeout(function()
    {
        t.dispatchEvent(new Event('keypress', {keyCode: 65}))
    }, 800);

}, false);
<textarea id="text"></textarea>
<button id="action">
    Do It
</button>

What do I miss that a is not added to the beginning of the textarea?

The purpose is to genuinely simulate an actual press of a key on the keyboard, NOT (re)setting the textarea value.

UPDATE: This is not a duplicate of this question.

(i) Most of the answers use jQuery.

(ii) I couldn't find a working example from those answers for the above case.

(iii) Actually, the above code was derived from that page.

Anyway, whether this is duplicate or not. You can read the question as: Why doesn't the above straightforward code work?

like image 615
Googlebot Avatar asked Oct 20 '18 21:10

Googlebot


1 Answers

Have to agree with Heretic Monkey - the event will 'fire' correctly however it will not actually perform the action (security - otherwise javascript could type and enter all sorts of crap into forms relatively easily!!!).

What you can do though is still create the event and simulate the result - it's a bit janky of course but this may help - this way you can still play with bubbling and other fun event-related aspects while still getting the result you're looking for. I'll admit it's pretty awkward though!

var el = document.getElementById('action');

el.addEventListener('click', function()
{
    var t = document.getElementById('text');
    t.value = 'A should be typed later';
    t.focus();
    t.setSelectionRange(0, 0);

    setTimeout(function()
    {
      var event = document.createEvent('Event');
      event.key = 65;
      event.initEvent('keypress');
      document.dispatchEvent(event);
    }, 800);

}, false);

document.addEventListener('keypress', function(e){
  let t = document.getElementById('text');
  let oldText = t.value;

    t.value = String.fromCharCode(e.key) + oldText;
    t.focus();
    t.setSelectionRange(1, 0);

});
<textarea id="text"></textarea>
<button id="action">
    Do It
</button>
like image 171
Mark Taylor Avatar answered Nov 06 '22 09:11

Mark Taylor