Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading