GenericUser01
GenericUser01

Reputation: 457

Printing each value of an array on a separate line Javascript

I have a program that involves Javascript to allow for interaction with a webpage. It's a baseball site so what I am doing is prompting the user to enter a month. The user can enter a number, like 6 for June, or the name of the month itself and the program will display all the games they are playing that month.

The way I did this was to create an array and store it with the game information. So the month of July would look something like this:

if(month == 7)    // July
{
    var gamesPlayed = ["7/1/16: Team1 @ Team2", "7/3/16: Team2 @ Team 4",
                       "7/4/16: Team3 @ Team2" , ... ,etc, ...];
}

In my main function (the one that executes when I push the Submit button), I want to print the array.

var schedule = getSchedule(July);

for(var i = 0; i < schedule.length; i++)
{
    document.getElementById("result").innerHTML = schedule[i] + "<br />";
}

For some reason this does not work. All it does it print the very last value in the array and not the whole thing. How come it is not printing the whole array? I tried to do document.write(schedule[i] + "<br />"); and that didn't do what I wanted. It printed it, but it printed it on a page by itself to where I couldn't time in a new month or go back to a homepage, etc. Is there a way to get this to print all the elements and not just the last one?

Upvotes: 2

Views: 13137

Answers (2)

Pointy
Pointy

Reputation: 413709

You can use .join() to combine the array into one string, and separate each entry by <br>:

document.getElementById("result").innerHTML =
  schedule.join("<br>");

There's no need for the self-closing / in <br>. More important, there's no need for the for loop. That code above will do the whole thing.

If you want a <br> after the last entry, just add it:

document.getElementById("result").innerHTML =
  schedule.join("<br>") + "<br>";

Upvotes: 8

Tigger
Tigger

Reputation: 9130

While Pointy's answer is correct it does not explain why your code is not working. I'll try and explain:

The error is in this for loop and how you are using innerHTML.

for(var i = 0; i < schedule.length; i++)
{
    document.getElementById("result").innerHTML = schedule[i] + "<br />";
}

Basically, on each iteration of the loop you are resetting the HTML of the result element instead of appending to it. The following small change is all that would have been needed.

for(var i = 0; i < schedule.length; i++)
{
    document.getElementById("result").innerHTML += schedule[i] + "<br />";
}

However, Pointy's answer is more efficient for sure.

Upvotes: 5

Related Questions