0

Here I am in a jQuery loop and all I am doing is making a string and appending it to a div. Very simple so far right?

Well I am also looping inside of my loop. The problem is my loop inside of my loop is generating the exact same result.

So my first loop I am looping through some TV Channels and my 2nd loop I am looping through some TV Shows. The problem is my TV shows are all the same for every channel. Pretty dumb cable network right?

How can I loop through all the TV Shows and attach them to the correct TV Channel?

shows='';
// loop through the tv channels
$(playlist).each(function(i,value){


// loop through the tv shows
$(value.videos).each(function(i,value){
    shows += '<div class="show"><a href="#"><p>'+tv show+'</p></a></div>';
}); end tv show loop

string = '<div class="channel">'+
            '<h1>value.name</h1>'+
            '<div class="shows">'+shows+'</div>'+
        '</div>';


$(string).appendTo('#streams');


}); // end tv chanel loop

What I want the html output to look like

<div class="channel">
<h1>channel name</h1>
<div class="shows">
    <div class="show"><a href="#"><p>show name</p></a></div>
    <div class="show"><a href="#"><p>show name</p></a></div>
    <div class="show"><a href="#"><p>show name</p></a></div>
</div>

<!-- repeat again -->
0

2 Answers 2

1

There are multiple problems

  1. the variable shows need to be reseted in every playlist loop
  2. value.name is a variable value so it cannot be added as a string
  3. tv show might has to be changed to tv.show

Try

// loop through the tv channels
$(playlist).each(function(i, value) {
    var shows = '';

    // loop through the tv shows
    $(value.videos).each(function(i, tv) {
        shows += '<div class="show"><a href="#"><p>' + tv.show
                + '</p></a></div>';
    }); // end tv show loop

    string = '<div class="channel">' + '<h1>' + value.name + '</h1>'
            + '<div class="shows">' + shows + '</div>' + '</div>';

    $(string).appendTo('#streams');

}); // end tv chanel loop

Demo: Fiddle

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

Comments

1

you need to use shows=''; inside the first loop

// loop through the tv channels
$(playlist).each(function(i,value){
shows='';
........
});

You need to empty the shows string for new channel.But you are not doing it.So it is appending to the previous string continuously

Comments

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.