Home > Software design >  failed to retrieve a local variable
failed to retrieve a local variable

Time:10-06

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 >
      <select  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 >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`);
}
    

CodePudding user response:

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 >
      <select  >
        <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 >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`)
}
  • Related