How to add eventlistener to menu js?

Viewed 291

I am trying to add an event listener when a menu item is clicked.

Why is menu.value undefined when an item is clicked?

Code:

let menu = document.getElementById("myDropdown");
menu.addEventListener("click", generateMap);

function generateMap(event) {
  if (menu.value == "all") {
    console.log("all");
  } else if (menu.value == "a1") {
    console.log("a1");
  } else if (menu.value == "a2") {
    console.log("a2");
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Select Building</button>
  <div id="myDropdown" class="dropdown-content">
    <option value="all">All</option>
    <option value="a1">A1</option>
    <option value="a2">A2</option>
  </div>
</div>

1 Answers

You are not using the proper HTML structure.

<option> tag is a child of <select> tag.

Add ID myDropdown to your <select> tag, and on that select tag you can attach the event listeners

let menu = document.getElementById("myDropdown");
menu.addEventListener("click", generateMap);

function generateMap(event) {
  if (menu.value == "all") {
    console.log("all");
  } else if (menu.value == "a1") {
    console.log("a1");
  } else if (menu.value == "a2") {
    console.log("a2");
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="dropdown">
  <select id="myDropdown">
  <option value="" selected disabled>Select Building</option>
    <option value="all">All</option>
    <option value="a1">A1</option>
    <option value="a2">A2</option>
  </select>
</div>

Related