0

I'm building a music site I have a section where you click a artist name an I use jquery to send the artist id to the DB and pull all songs under his name, then I list them in a div on the page as links.

My problem is, whenever I use .text or .val to amend the song titles in a div, if he has 2 songs, it only shows the first song title.

However, if I use .append, when I click 1 artist name, it pulls all his song fine, but if I click another artist name on the same page it adds his songs below the ones for the previous artist.

Only list 1 song, even if there is 2;

$.each(data.resultData, function(key, value) {
    $('value.SongTitles').text(value.artistName +':' + songTitle).fadeIn(); 
});

List all songs fine, but doesn't clear previous artist songs after a new artist name is clicked;

$.each(data.resultData, function(key, value) { 
    $('value.SongTitles').append(value.artistName +':' + songTitle).fadeIn(); 
});
code4_days
  • 27
  • 3

4 Answers4

1

Clear the contents each time before populating it.

$('value.SongTitles').text('');
$.each(data.resultData, function(key, value) { 
    $('value.SongTitles').append(value.artistName +':' + songTitle).fadeIn(); 
});
jbabey
  • 45,965
  • 12
  • 71
  • 94
0

Well, first option rewrites the content of 'value.SongTitles' on each iteration, so that's why only one song appears. You could use your second option cleaning 'value.SongTitles' first, like this:

$('value.SongTitles').text("");
$.each(data.resultData, function(key, value) { 
    $('value.SongTitles').append(value.artistName +':' + songTitle).fadeIn(); 
});
Gonzalo Quero
  • 3,303
  • 18
  • 23
0

If you use .append(), as the name implies, it will append it at the end. Try .html(), it will clear all previous content.

$('value.SongTitles').html(value.artistName +':' + songTitle).fadeIn(); 
wtrevino
  • 4,831
  • 2
  • 15
  • 9
0

You could either clear before the $.each loop, like this:

$('value.SongTitles').html('');

$.each(data.resultData, function(key, value) { 
    $('value.SongTitles').append(value.artistName +':' + songTitle).fadeIn(); 
});

Or you could check the key, like this:

$.each(data.resultData, function(key, value) { 
        if(key == 0){
           $('value.SongTitles').html('');
        }
        $('value.SongTitles').append(value.artistName +':' + songTitle).fadeIn(); 
});

Note, I prefer to use .html() for the reasons listed here: What is the difference between jQuery: text() and html() ?

Community
  • 1
  • 1
  • since his data contains artist names and song titles, i don't think we need to worry about escaping HTML, but it's a good thought for the OP. – jbabey Feb 21 '12 at 17:34