Reputation: 225
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!
Upvotes: 0
Views: 103
Reputation: 1764
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
})
Upvotes: 1
Reputation: 1564
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>
Upvotes: 2