Search code examples
javascripthtmldomdropdown

How to get value of dynamically created dropdown list?


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!


Solution

  • 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>