Home > Blockchain >  An addEventListener with keydown results in an empty string upon the first key in a textarea
An addEventListener with keydown results in an empty string upon the first key in a textarea

Time:11-15

I have a textarea tag that takes in values to use for something else. When I press on a key, the value of it is an empty string. However, the keys pressed after the first key show up just fine. For instance, if I type, "hello" the value would be, "ello". I want it so the value of the first key would show up.

Here's my code,

const editor = document.getElementById(‘editor’);
editor.addEventListener('keydown', (event => {
    let value = editor.value;
    console.log(value);
}));

This is my HTML for the textarea, in case if needed,

<textarea autofocus id="editor"></textarea>

Thanks.

CodePudding user response:

To see all the characters as you type use the keyup rather than keydown as the event type.

editor.addEventListener('keyup',function(e) {
    let value = this.value;
    let preview=document.getElementById('preview');
    console.log(value);
    preview.innerHTML=value;
});
<textarea autofocus id="editor"></textarea>
<div id='preview'></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related