Ezhno Ezhno - 11 days ago 6
Javascript Question

Check if a textarea changes, and if so, write it's value somewhere

I have one textarea

#text-g
and one div
#textg
. I'd like to make a script for when the textarea changes (Someone type in it), the div display the text.

I've made this pretty simple code, but of course it's not working because there's no event.

function myFunction() {
var text1 = document.getElementById('text-g').value;
document.getElementById('textg').value = text1.val;
}


Could someone please explain me how these events work ?
And does my two-codes are enough, with the event, to do what I would like to achieve ?

Answer

You can use oninput event to track text input.

You can read more here about oninput event.

And one more thing DIV element won't have attribute value by default so used innerHTML to populate div#textg with text from textarea#text-g

function myFunction() {
document.getElementById('textg').innerHTML = document.getElementById('text-g').value;
}
<textarea id="text-g" oninput="myFunction();"></textarea>

<div id="textg"></div>

Comments