Kevinkuijer
Kevinkuijer

Reputation: 130

Javascript onclick variable not working

Can someone tell me why this is not working:

<a href="#" onclick="play('playlist1');">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(id);
}

And this is working:

<a href="#" onclick="play();">Play Playlist1</a>
function play(){
    myPlaylist.setPlaylist(playlist1);
}

There is also a variable called playlist1

var playlist1 = [
    {
        title:"Title",
        artist:"artist",
        mp3: "pathtofile"
    }];

So i need the first one to set the variable to get the right playlist.

It is the same value so it really weird, but i need the first one to work

Can someone help me?

Upvotes: 0

Views: 66

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

If your first, non-working example, you are passing 'playlist1' as a string, rather than the playlist1 variable. Simply removing the single quotes should be enough to fix it.

Example:

<a href="#" onclick="play(playlist1);">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(id);
}

Another solution would be to look up the variable by the string name via window[id].

Example:

<a href="#" onclick="play('playlist1');">Play Playlist1</a>
function play(id){
    myPlaylist.setPlaylist(window[id]);
}

Upvotes: 1

Related Questions