How can I append a list of text into a textarea?
<textarea id="alltext"></textarea>
<ol>
<li onclick="addText(Hello')">Hello</li>
<li onclick="addText(World')">World</li>
<li onclick="addText(Earthlings')">Earthlings</li>
</ol>
<script>
var Alltext = "";
function addText(text) {
Alltext += text
}
document.getElementById("alltext").value = Alltext;
</script>
This is quite inefficient as the list is actually very long. The text added is exactly the value I see on the HTML so there’s no need to type it twice right?
Is there any better methods?
Use event delegation by assigning the
onclickto the<ol>. Then pass theeventobject as the argument, and using that, grab the text from the clicked element.Note that this method of passing the
eventobject works in older IE as well as W3 compliant systems.