0

I'm trying to get the current selected text value of a dropdown menu with javascript as a global variable.

At the moment I'm having the problem that the global variable desc is empty and it shows "undefined" in the console.

This is the script:

    var desc;
    const areaSelect = document.querySelector(`[id="test"]`);

    areaSelect.addEventListener(`change`, (e) => {
        const select = e.target;
        const value = select.value;
        desc = select.options[select.selectedIndex].text;
          
    });
    
console.log(desc);

And I´ve made the JSFiddle.

Berstos
  • 179
  • 10
  • 2
    What happens if you move the `console.log()` inside the event listener? – Code-Apprentice May 16 '21 at 02:27
  • Your change event listener function only executes when a change occurs. However, your `console.log(desc)` will run before that change occurs when your script initially runs, so it will show `undefined` as it hasn't been set yet. – Nick Parsons May 16 '21 at 02:30

0 Answers0