1

I see that variations of this question has been asked several times before but none of the solutions seem to work for me unfortunately. I'm still a beginner in JavaScript hence I'm not sure what's happening here to debug this properly and what exactly to read up in the documentation.

Basically, I want to access and store the selected value of a drop down list inside a change event handler.

In my current approach, I am able to output the change event inside the event handler. But I cannot seem to assign it to a global variable outside of it, which I require for some other parts in my code.

Here is my MWE:

let dd = document.getElementById('dropDownMenu')
let dropDownChoice;

dd.addEventListener('change', function(e){
  dropDownChoice = e.target.value;
  console.log(dropDownChoice); // This outputs the selected item whenever the drop down is changed
});

console.log(dropDownChoice) // This does not output anything

1 Answer 1

2

It's not outputting anything becasue that line is executed before you make a selection. If you add a button and call a function by clicking it after you select, you will see that the value is there:

document.querySelector('button').addEventListener('click', () => console.log(dropDownChoice))
Sign up to request clarification or add additional context in comments.

Comments

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.