How to Create a Dropdown Menu with Checkboxes in HTML and JavaScript?

Estimated read time 2 min read

You can create a dropdown menu with checkboxes in HTML and JavaScript by dynamically creating HTML elements and adding event listeners to handle user interactions. Here’s a basic example:

<div id="dropdown-container">
  <button id="dropdown-button">Select Options</button>
  <div id="dropdown-menu" style="display: none;">
    <label><input type="checkbox" value="option1"> Option 1</label><br>
    <label><input type="checkbox" value="option2"> Option 2</label><br>
    <label><input type="checkbox" value="option3"> Option 3</label><br>
  </div>
</div>

<script>
  let container = document.getElementById('dropdown-container');
  let button = document.getElementById('dropdown-button');
  let menu = document.getElementById('dropdown-menu');

  button.addEventListener('click', function() {
    menu.style.display = (menu.style.display === 'none') ? 'block' : 'none';
  });

  container.addEventListener('click', function(event) {
    if (event.target.tagName === 'INPUT') {
      console.log(event.target.value + ' was selected.');
    }
  });
</script>

In this example, a button and a div element containing the checkboxes are created, along with an outer div element to serve as a container. The button has an event listener attached that listens for a click event, and toggles the display of the div element containing the checkboxes. The container has an event listener attached that listens for click events on its children, and if the target of the click event is an input element, a message is logged to the console indicating which option was selected.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply