Udara Suranga Udara Suranga - 4 months ago 22
Javascript Question

how to pass an array to function in jquery jaudio

by using this function I tried to add several objects to temp array.



var temp = [];

function addSong(id) {
var button = $('#' + id + ''); // Button that triggered the modal
var file = button.data('file'); // Extract info from data-* attributes
var thumb = button.data('thumb'); // Extract info from data-* attributes
var trackName = button.data('track_name'); // Extract info from data-* attributes
var trackArtist = button.data('track_artist'); // Extract info from data-* attributes
var trackAlbum = button.data('track_album'); // Extract info from data-* attributes

temp += "{file:'" + file + "',thumb:'" + thumb + "',trackName:'" +
trackName + "',trackArtist:'" + trackArtist + "',trackAlbum:'" + trackAlbum + "'},";

$("#player").jAudio({
playlist: []
});
}




Answer

You need to pass an array of objects not a string. Like the sample below

$("#player").jAudio({
    playlist: [{
        file: "resources/tracks/01.mp3",
        thumb: "resources/thumbs/01.jpg",
        trackName: "Track 1",
        trackArtist: "Artist 1",
        trackAlbum: "Album",
    }, {
        file: "resources/tracks/02.mp3",
        thumb: "resources/thumbs/02.jpg",
        trackName: "Track 2",
        trackArtist: "Artist 2",
        trackAlbum: "Album",
    }]
});

So change your temp variable to something like

var temp =  {
     file: file,
     thumb: thumb,
     trackName: trackName,
     trackArtist: trackArtist,
     trackAlbum: trackAlbum
 };

and then use it in the array

  $("#player").jAudio({
        playlist: [temp]
  });

Based on the updated question, you can modify your js function to something like this

 var temp = [];

 function addSong(id) {

     var button = $('#' + id + ''); // Button that triggered the modal
     var file = button.data('file'); // Extract info from data-* attributes
     var thumb = button.data('thumb'); // Extract info from data-* attributes
     var trackName = button.data('track_name'); // Extract info from data-* attributes
     var trackArtist = button.data('track_artist'); // Extract info from data-* attributes
     var trackAlbum = button.data('track_album'); // Extract info from data-* attributes

     var tempObj = {
         file: file,
         thumb: thumb,
         trackName: trackName,
         trackArtist: trackArtist,
         trackAlbum: trackAlbum
     };

     temp.push(tempObj);

     $("#player").jAudio({
         playlist: temp
     });
 }
Comments