failed to retrieve a local variable

Issue

I’m a JS self-learner. I want to make a playlist using select HTML element and a button. I managed to choose and console log the value from the but I can’t use it to create the name of an MP3 file. Can anyone give me a hand? I read that var has both local and global scope. Or how can I retrieve the value from the selectTrack function. Sorry if for some of you it may be a trivial question but I’m still on the stage of figuring out the functions in JS.

    <div class="playlist-container">
      <select class="playlist-selector" onchange="selectTrack()">
        <option value="default">default</option>
        <option value="track1">Owner of a Lonely Heart</option>
        <option value="track2">Somebody's Baby</option>
        <option value="track3">Easy Lover</option>
      </select>
      <button class="play-btn">play</button>
    </div>
  const playBtn = document.querySelector(".play-btn");
let mySong = ``

function selectTrack() {
    var mySongSelected = document.querySelector(".playlist-selector").value;
    console.log(mySongSelected);
  }

playBtn.addEventListener("click", playTrack);

function playTrack() {
    console.log(`${mySongSelected}.mp3`);
}
    

Solution

I removed your onchange and selectTrack function, then declared mySong as undefined and initialized it inside playTrack with the queryselector.value as its value. Now it seems to work fine.

HTML

  <div class="playlist-container">
      <select class="playlist-selector" >
        <option value="default">default</option>
        <option value="track1">Owner of a Lonely Heart</option>
        <option value="track2">Somebody's Baby</option>
        <option value="track3">Easy Lover</option>
      </select>
      <button class="play-btn">play</button>
    </div>

Javascript

const playBtn = document.querySelector('.play-btn')
let mySong;

playBtn.addEventListener('click', playTrack)

function playTrack() {
  mySong = document.querySelector('.playlist-selector').value
  console.log(`${mySong}.mp3`)
}

Answered By – Adam Carlsson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published