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?