0

I have the following list:

<ul>
    <li onclick="populateComment(..this.)">very good </li>
    <li onclick="populateComment(..this.)">not so good</li>
    <li onclick="populateComment(..this.)">no t.....</li>
</ul>

and javascript:

function populateComment() {

    document.getElementById("COMMENT").value = document.getElementById("COMMENT").value + 'THE_STRING_VALUE_FROM_THE_LIST';

}

So the idea is that I have a textarea, which I fill by clicking on the list.

So if I click on the first list, the text "very good" should be appended to the textarea. But I dont want to retype the text "very good" in my function, can I take it directly with something as an argument like this.value.. so it automatically takes the string between the <li> ...</li>

Thank you for your time.

3 Answers 3

3

You're looking for:

this.textContent || this.innerText

this.textContent is supported in all decent browsers, this.innerText is needed for older versions of IE.

Instead of duplicating the onclick handler multiple times, you can also bind a listener to the <ul> element:

// Replace <ul> with <ul id="populatefrom">
document.getElementById("populatefrom").onclick = function(ev) {
    ev = ev || window.event; //Backwards compatible with IE
    var target = ev.target;
    if (target.nodeName.toLowerCase() == "li") {
        document.getElementById("COMMENT").value += target.textContent || target.innerText;
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

@Adnan Updated answer for an easier implementation. I have used the simple .onclick = .. form to prevent having to define conditions for addEventListener (decent browsers) or attachEvent (IE).
1

If you don't have anything other than a simple bit of text, you could also use:

this.firstChild.nodeValue;

However if there are any nodes at all (bold, span, or anything else other than text... even an HTML comment) then this won't work and you need the textContent/innerText combo Rob W gave.

Comments

-1

Sure you could do this with jQuery like so (didn't test this yet):

<ul>
    <li class="populateComment">very good </li>
    <li class="populateComment">not so good</li>
    <li class="populateComment">no t.....</li>
</ul>

and your jQuery:

$('.populateComment').click(function(){
  $('#textboxID').val($(this).html());
});

Working jsfiddle: http://jsfiddle.net/zEaam/

2 Comments

-1 for bringing in jQuery just for something so incredibly basic.
Also, if you're using jQuery, you'd better make full use of it: $("li").click(function(){$("#textboxId").val($(this).html());});

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.