1

I'm trying to print an array to a textarea in JavaScript. My current code only prints the first element instead of all four, and I don't know why.I have tried using a regular for loop as well, but that doesn't make a difference.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        var listArray = function()
        {
            var people = ["Ben", "Joel", "Mary", "Tina"]; 
            var scores = [88, 98, 100, 78]; 

            for (var key in people)
            { 
                var obj = people[key]; 
                var num = scores[key];

                var string = obj + ", " + num + "\n"; 

                document.getElementById("box").innerHTML = string; 
            }
        }

        window.onload = function()
        {
            document.getElementById("show_score").onclick = showHighScore; 
            document.getElementById("list_array").onclick = listArray; 
        }
        </script>
    </head>
    <body>
        <form id="high_score" name="high_score" action="highScore.html" method="get">
            <label>Results</label>
            <br>
            <textarea cols="50" rows="4" id="box"></textarea>
            <br>
            <input type="button" value="List Array" id="list_array" onclick="listArray">
            <br>
            <input type="button" value="Show Best Score" id="show_score" onclick="showHighScore">
        </form>
    </body>
</html>
1
  • You just need to append, .innerHTML = ... will overwrite. .innerHTML += ... appends. Also note showHighScore isn't defined. Commented Sep 27, 2014 at 1:43

1 Answer 1

3

That is because of this line

document.getElementById("box").innerHTML = string;

So what you are saying, replace the content of textbox with the content of string. So at the end it just have the value of last element.

use this instead

document.getElementById("box").innerHTML += string; 

So it will append the next record after previous one.

There is one more problem, on 23rd line it sasys showHighScore is not defined.

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

1 Comment

I was also facing the same thanks a ton! for this answer.

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.