简体   繁体   中英

Javascript: textContent based on textLength

Hi all (first poster so don't shoot me...yet):

I'm trying to alter a textarea based on the textlength.

My code is as follow:

<script type="text/javascript">
            function addComment(){
                var commentBank = document.getElementById("commentBank");
                var selectedComment = commentBank.options[commentBank.selectedIndex].text;
                var currentComment = document.getElementById("comment");

                console.log(currentComment.textLength);

                if(currentComment.textContent == "Add comment here" ){
                    currentComment.textContent = selectedComment;
                }else if(currentComment.textLength == 0){
                    console.log("Trying to add "+selectedComment);
                    currentComment.textContent = "selectedComment";
                }
                else{
                currentComment.textContent += ". " + selectedComment;
                }


            }
            </script>

What I'm trying to do is get the selected item from a option (called commentBank), from this, get the text selected and add it to a textarea (called comment).

The issue at present is that when currentComment.textContent () is equal to 0, it doesn't add the text to the textarea. It does output to the log however, doesn't update the textarea to add the text, so the if statement is working.

Any ideas? Thanks in advanced.

This is the code snippet you're talking about:

        }else if(currentComment.textLength == 0){
            console.log("Trying to add "+selectedComment);
            currentComment.textContent = "selectedComment";

The reason it doesn't actually add the comment is because you are setting currentComment.textContent to the string "selectedComment" , not the value . That's why it prints okay in your log (because you're logging the value). Change that line to:

currentComment.textContent = selectedComment;

(Note the absence of the quotation marks, which creates a string with the literal value selectedComment .)

Try using value instead of textContent , to write the content of a textarea.

I don't know all browsers, but in some of them, textContent is read only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM