0

I instantiate a list of users in my DOM and then tie their name to the dropdown list. So they are not created until page load. I'm having trouble trying to target the <option> tag and access it's value.

JS DOM Function

  let userDropDownList = userInstantiation.reduce((usersHTML, user) => {
    usersHTML += `<option class="nav__div__one__dropdown__choice" value="${user.id}">${user.name}</option>`
    return usersHTML;
  }, '')
  navDivDropdown.innerHTML = userDropDownList
}

I've tried to loop through the <option> tags but I'm returning empty an array. My wrapper in my index.html is <select class="nav__div__one__dropdown" name="users"></select>

I'm attempting to get the value so that I can tye the user.id to the User instance and access those class methods. Any tips would be greatly appreciated!

2 Answers 2

2

You can do it using onchange event on the select input like so:

<select onchange="changed(this)"></select>

function changed(option){
 console.log(option.value);
}

Here is a working snippet

let userInstantiation = [{id: 1, name: 'user1'},{id: 2, name: 'user2'}];
let userDropDownList = userInstantiation.reduce((usersHTML, user) =>
    usersHTML += 
    `<option class="nav__div__one__dropdown__choice" value="${user.id}">${user.name}</option>`
  , '')
  document.querySelector(".nav__div__one__dropdown").innerHTML = userDropDownList;
  
function changed(option){
 console.log(option.value);
}
<select class="nav__div__one__dropdown" onchange="changed(this)" name="users"></select>

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

Comments

1

you would go about it this way

document.querySelector('nav__div__one__dropdown').addEventListner('change',(e)=>{
  const userId=e.target.value; 
  //here do your user tying logic 
})

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.