Search code examples
jqueryparameter-passingjplayer

How do I pass JQuery text parameter as a variable


For the program JPlayer, I want to create an arbitrary amount of {..},{..} inside the jQuery statement's playlist parameter. The "newtest" variable will have the format {mp3: filename}, {mp3: filename2}... I can't seem to find the right syntax to create "newtest".

This code works:

var filename = "/mymusic/" + mydata[1];
// var newtest = new String('{ mp3: filename }');
script(type='text/javascript').
    //<![CDATA[
    $(document).ready(function() {
        var myPlaylist = new jPlayerPlaylist({
                jPlayer: "#jquery_jplayer_N",
                cssSelectorAncestor: "#jp_container_N"
            },
            [
                // newtest
                {
                    mp3: filename
                }
            ],....

This code doesn't create an error but won't access my music file:

var filename = "/mymusic/" + mydata[1];
var newtest = new String('{ mp3: filename }');
script(type='text/javascript').
    //<![CDATA[
    $(document).ready(function() {
        var myPlaylist = new jPlayerPlaylist({
                jPlayer: "#jquery_jplayer_N",
                cssSelectorAncestor: "#jp_container_N"
            },
            [
                newtest
                // {
                // mp3: filename
                //  }
            ],...     

Both answers below work:

var newtest = { mp3: filename };

var myplayList = [
    { mp3: filename1 },
    { mp3: filename2 }
]

Thanks


Solution

  • Why not create the values first, in a more readable manner, and then pass the data in?

    This way, you can pass the proper structure.

    Your parameter is an object. The newtest value of your parameter is actually a collection - an array of objects.

    In the code below, it's simpler to see what's going on:

    var params = {
        jPlayer: '#jquery_jplayer_N',
        cssSelectorAncestor: '#jp_container_N'
    }
    
    // This is an array of objects
    var playList =[
        { mp3: 'filename1' },
        { mp3: 'filename2' },
        { mp3: 'filename3' }
    ]
    
    var myPlaylist = newjPlayerPlaylist(params, playList);