Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery "undefined" prints when appending to html element

I'm making a jQuery MP3 player. The song structure is first generated (including the information about the song), and then the structure is appended to a div using jQuery like this:

function loadFromPlaylist(playlist) {
    var songsStructure;

    for (var i=0; i<playlist.length; i++) {
        songsStructure +=
        "<div id='song" + i + "'>" +
            "<span class='mpPlaylistArtist'>" + playlist[i].artist + "</span>" +
            "<span class='mpPlaylistSong'>" + playlist[i].song + "</span>" +
            "<span class='mpPlaylistAlbum'>" + playlist[i].album + "</span>" +
        "</div>";
    }

    $('#mpTracks').append(songsStructure);
}

This works perfectly except for one thing. When the items are displayed in the browser, a string ("undefined") is printed above the songs, like so:

<div id="mpTracks">
    "undefined"
    <div id="song0">...</div>
    <div id="song1">...</div>
</div>

Googling this problem yielded alot of related problems but that didn't help me.

Does anyone know what the problem might be?

like image 507
judehall Avatar asked Nov 28 '22 03:11

judehall


2 Answers

Initialize your variable to an empty string, before using it:

var songsStructure = '';

You did not set an initial value, so it is set to undefined. According to JS rules for concatination, this undefinedis then concatenated with the strings generated by the for loop leading to your result.

like image 105
Sirko Avatar answered Nov 30 '22 22:11

Sirko


You have to initialize the songsStructure variable.

Write

 function loadFromPlaylist(playlist) {
        var songsStructure="";

and your problem will be solved.

like image 27
Daniele B Avatar answered Nov 30 '22 22:11

Daniele B