Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append text to textarea with javascript

Tags:

javascript

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?

like image 408
Emerson F Avatar asked Jan 21 '13 18:01

Emerson F


People also ask

Can I add value to textarea?

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.

Can I put Div inside textarea?

You cannot place HTML elements inside a text area, only text content. only text content covers that part.

Can we use value attribute in textarea?

From the MDN documentation: " <textarea> does not support the value attribute".


2 Answers

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.

like image 50
the system Avatar answered Oct 05 '22 08:10

the system


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> 
like image 36
Carl Avatar answered Oct 05 '22 08:10

Carl