0

The code below always shows opt 5 instead of the one I clicked.

In HTML :

 <div id = "dropdown_1" class="dropdown">
    <button onclick="dropdown_toggle()" class="dropbtn">Dropdown</button>
    <div id="myDropdown" class="dropdown-content">
    </div>
 </div>

In another js file :

   var select = document.getElementById("myDropdown");
   var options = ["opt 1", "opt 2", "opt 3", "opt 4", "opt 5"];


  for(var i = 0; i < options.length; i++) {
      var opt = options[i];
      var el = document.createElement("a");
      el.textContent = opt;
      el.value = opt;
      el.onclick = function(event) {
        
        console.log(opt);
        
      }
      select.appendChild(el);
  }   
Justin
  • 327
  • 3
  • 13
  • 2
    `const opt`, not `var opt`. Even better: Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296). Use the [event argument](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback), [`target`](//developer.mozilla.org/en/docs/Web/API/Event/target), [`closest`](//developer.mozilla.org/en/docs/Web/API/Element/closest). – Sebastian Simon Mar 30 '22 at 03:08
  • 1
    Sebstian's comment is very astute. My first thought was change the console.log to `console.log(event.target.innerHTML);`, which will also work. – Nicolas Goosen Mar 30 '22 at 03:12

0 Answers0