1

I'm trying to get multiple bandnames after another using an each loop but all i'm getting is the final name from the loop. can somebody tell me what i'm doing wrong.

XML structure:

<resultsPage> <results> <event type="concert"> <performance displayName="bandname1"></performance> <performance displayName="bandname2"></performance> <performance displayName="bandname3"></performance> </event> </results> </resultsPage> 

ajax:

$.ajax({ url: 'xml/timeline.xml', dataType: 'xml', success: function(data){ $(data).find('resultsPage results event').each(function(){ var type = $(this).attr('type'); var band = $(this).find('performance artist').each(function(){ name = $(this).attr('displayName'); }) $('.timeline ul').append( '<li>A '+type+' played by '+name+'</li>' ); }); }, error: function(){ $('.timeline').text('Failed to get feed'); } }); 

1 Answer 1

1

You are overwriting the name variable in each iteration. Change to:

$(data).find('resultsPage results event').each(function(){ var type = $(this).attr('type'); var band = $(this).find('performance artist'); var length = $(band).length; $(band).each(function(index, element){ name += $(this).attr('displayName'); if (index < length-1) { name += ", "; } }); $('.timeline ul').append( '<li>A '+type+' played by '+name+'</li>' ); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

then your getting something like this: A concert played by bandname1, A concert played by bandname2. but i want something like: A concert played by bandname1, bandname 2, bandname3
I've updated the answer. Note the += operator and the concatenated ", ".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.