Reputation: 845
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?
Upvotes: 58
Views: 160424
Reputation: 9336
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.
Upvotes: 93
Reputation: 511
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>
Upvotes: 10