2

From a .js file, I am getting name of albums and loading them into a select menu with the use of this function:

function loadToSelect(id, list){
  for (var i in list) {
    var option = document.createElement("option");
    option.innerText = list[i].title;
    document.getElementById(id).appendChild(option);
  }
}

What I now need to do is load the songs from that album in another select box. I tried the following:

This function use loadToSelect to choose to load the "songs" part of the file and creates an options menu from the number of tracks

function loadToSongs(index) {
  loadToSelect("songs", albums[index].tracks);
  document.getElementById("songs").size = albums[index].tracks.length;
}

The next function is supposed to get the index of the selected album and load the songs accordingly

function songsFromAlbum () {
  loadToSongs(getElementById("albums").selectedIndex);
}

Lastly, I call these to start the functions

loadToSelect ("albums", albums);
document.getElementById("albums").onchange= songsFromAlbum()

What works so far is loading the albums into a text box, but loading the song doesn't seem to work, any help or advice would be appreciated

EDIT: I should mention I am no allowed to use JQuery.

1 Answer 1

2

Enjoy

function loadToSelect(id, list){
  document.getElementById(id).innerHTML = '';
  for (var i in list) {
    var option = document.createElement("option");
    option.innerText = list[i].title;
    document.getElementById(id).appendChild(option);
  }
}

function loadToSongs(index) {
  loadToSelect("songs", albums[index].tracks);
}

function songsFromAlbum () {
  loadToSongs(document.getElementById("albums").selectedIndex);
}

document.getElementById("albums").addEventListener("change", function(){
  songsFromAlbum();
});


var albums = [{title: 'Red', tracks: [{title: 'Red Song 1'}, {title: 'Red Song 2'}]}, {title: 'Blue', tracks: [{title: 'Blue Song 1'}, {title: 'Blue Song 2'}]}, {title: 'Green', tracks: [{title: 'Green Song 1'}, {title: 'Green Song 2'}]}];

loadToSelect ("albums", albums);

document.getElementById("albums").onchange= songsFromAlbum()
<select id="albums"></select>

<select id="songs"></select>

Sign up to request clarification or add additional context in comments.

1 Comment

Incredidble!! Thank you so much, I really appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.