61

How can I append a list of text into a textarea?

var Alltext = "";

function addText(text) {
  Alltext += text
}
document.getElementById("alltext").value = Alltext;
<textarea id="alltext"></textarea>

<ol>
  <li onclick="addText('Hello')">Hello</li>
  <li onclick="addText('World')">World</li>
  <li onclick="addText('Earthlings')">Earthlings</li>
</ol>

This is quite inefficient, as the list is actually very long. The text added is exactly the value I see in the HTML, so I assume there's no need to type it twice.

Are there any better methods?

3
  • 1
    So are you looking for a means to add the text as many here have answered, or are you looking for a means to build the list in code instead of manually? Commented Jan 21, 2013 at 18:42
  • 1
    the system had the answer for this. Thanks for the time to read! Commented Jan 21, 2013 at 18:56
  • You can also use setRangeText (), to append text to the TextArea. e.g. textArea.setRangeText (newText, textArea.textLength, textArea.textLength); Commented Aug 20 at 10:52

2 Answers 2

95

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think this nailed it. Thank you for your kind patience!
Do you think there is a possibility to add word in the middle of the text?
11

Give this a try:

$(document).ready(function() {
  $("li").click(function() {
    $('#alltext').append($(this).text());
  });
});
li:hover {
  cursor: hand;
  cursor: pointer;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<h2>List items</h2>
<ol>
  <li>Hello</li>
  <li>World</li>
  <li>Earthlings</li>
</ol>
<form>
  <textarea id="alltext"></textarea>
</form>

3 Comments

Using jQuery for this tiny task would be massive overkill.
Thanks Carl, but I would prefer not to use jquery.. Thanks a million for your time anyway!
Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.