Append text to textarea with javascript
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>