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?
To add a value into a textarea, you can add to the value property of the input via document. getElementById. Reference this element and change the value: document.
You cannot place HTML elements inside a text area, only text content. only text content covers that part.
From the MDN documentation: " <textarea> does not support the value attribute".
Use event delegation by assigning the onclick
to the <ol>
. Then pass the event
object as the argument, and using that, grab the text from the clicked element.
function addText(event) { var targ = event.target || event.srcElement; document.getElementById("alltext").value += targ.textContent || targ.innerText; }
<textarea id="alltext"></textarea> <ol onclick="addText(event)"> <li>Hello</li> <li>World</li> <li>Earthlings</li> </ol>
Note that this method of passing the event
object works in older IE as well as W3 compliant systems.
Give this a try:
<!DOCTYPE html> <html> <head> <title>List Test</title> <style> li:hover { cursor: hand; cursor: pointer; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("li").click(function(){ $('#alltext').append($(this).text()); }); }); </script> </head> <body> <h2>List items</h2> <ol> <li>Hello</li> <li>World</li> <li>Earthlings</li> </ol> <form> <textarea id="alltext"></textarea> </form> </body> </html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With