checkbox inside a select option using JavaScript

Simple tutorial to use Checkbox inside Select Option using JavaScript

Learn how to enhance user experience with a checkbox inside select option using JavaScript. Follow this simple tutorial for interactive selection features.

In this tutorial, we will explore a simple and effective way to enhance user experience by adding a checkbox inside a select option using JavaScript. By combining the functionality of checkboxes with the dropdown nature of a select element, we can provide users with a more interactive and intuitive interface for selecting multiple options.

This tutorial will guide you through setting up the HTML structure, styling the checkboxes, implementing JavaScript functionality to handle checkbox selections, and testing the final result. By the end of this tutorial, you will have a practical understanding of how to create a dynamic and user-friendly dropdown menu with checkboxes using JavaScript.

Setting up the HTML

To set up the HTML for incorporating a checkbox inside a select option using JavaScript, follow these steps:

Create a basic HTML structure:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Checkbox with Select</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="styles.css" />
    <script type="module" src="script.js"></script>
  </head>
  <body>
    <h1>Checkbox inside Select Option</h1>
    <div class="select-container">
      <div class="select-input-box">
        <div class="select-input-text">Selected(0)</div>
        <div class="select-input-dropdown-icon"><</div>
      </div>
      <div class="select-options"></div>
    </div>
  </body>
</html>

In the above code, we also add below style elements to add some stylings and functionality,

* {
  box-sizing: border-box;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0;
  font-family: system-ui, sans-serif;
  color: black;
  background-color: white;
}

h1 {
  text-align: center;
  font-weight: bold;
  font-size: 1.5rem;
}

.select-container {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 30px;
  width: 200px;
  padding: 0 16px;
  border: 1px solid #d4d4d4;
  border-radius: 4px;
}

.select-container:hover {
  cursor: pointer;
}

.select-input-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.select-input-text {
  font-size: 13px;
  color: #1d1d1d;
}

.select-input-dropdown-icon {
  font-size: 13px;
  transform: rotate(-90deg);
}

.select-options {
  position: absolute;
  top: 29px;
  left: 2px;
  width: 195px;
  height: 190px;
  border: 1px solid #d4d4d4;
  display: none;
  flex-direction: column;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 3px 6px;
}

label {
  font-size: 13px;
  color: #1d1d1d;
}

.options-container {
  width: 100%;
  padding: 8px;
}

.options-container:hover {
  background-color: #eef5fd;
}

label.options {
  display: flex;
  gap: 8px;
  align-items: center;
}

In the above code, as you observe, we are using select-container div which acts as our select element. Inside it, we have two elements, select-input-box and select-options. In select-input-box we have two children,

  • select-input-text :- It acts as a label that informs users how many options have been selected
  • select-input-dropdown-icon :- It is a drop-down icon that indicates user that we have dropdown items,

And select-options is a container that has all the options with checkboxes, and by default it is set to be display:none. When a user clicks on select-container, options containers appear.

Also read, What is the Best Way to Optimize CSS?

Make DropDown appears by clicking on select container

  • We will get the reference on select-container using document.getElementsByClassName().
  • We will initialize a variable show with a boolean value true.
  • We will add a click event listener to select-container, and when clicked it executes a function.
  • Inside the event listener function, there is a conditional statement that checks the value of the show variable.
  • If show is true, it means the element should be displayed, so it sets the style of selectElement to display: 'flex'; and then sets show = false.
  • If show is false, it means the element should be hidden, so it sets the style of selectElement to display: 'none'; and then sets show = true.
// Select the element with the class 'select-container'
const selectContainer = document.getElementsByClassName('select-container')[0];

// Initialize a variable to track the display state
let show = true;

// Add a click event listener to the selectContainer
selectContainer.addEventListener('click', () => {
    // Check the current state of the show variable
    if (show) {
        // If show is true, display the selectElement
        selectElement.style.display = 'flex';
        // Update show to false since the element is now displayed
        show = false;
    } else {
        // If show is false, hide the selectElement
        selectElement.style.display = 'none';
        // Update show to true since the element is now hidden
        show = true;
    }
});

Add options inside the select-options element

We will dynamically add the options to the select dropdown using the below function.

  • const selectElement = document.getElementsByClassName('select-options')[0];: This line selects the first element in the HTML document that has the class name ‘select-options’ and assigns it to the variable selectElement.
  • const options = ['Option 1', 'Option 2', 'Option 3', 'Option 4', 'Option 5'];: This line creates an array named options that contains five string elements representing different options.
  • The code then uses a forEach loop to iterate over each element (option) in the options array:
    • const checkbox = document.createElement('input');: Creates a new input element of type checkbox.
    • checkbox.type = 'checkbox';: Sets the type of the created input element to the checkbox.
    • checkbox.value = option;: Sets the value attribute of the checkbox element to the current option.
    • checkbox.id = option;: Sets the id attribute of the checkbox element to the current option.
    • const label = document.createElement('label');: Creates a new label element.
    • label.classList.add('options');: Adds the class ‘options’ to the label element.
    • label.appendChild(checkbox);: Appends the checkbox input element to the label.
    • label.appendChild(document.createTextNode(option));: Appends a text node with the current option text to the label.
    • const optionElement = document.createElement('div');: Creates a new div element.
    • optionElement.classList.add('options-container');: Adds the class ‘options-container’ to the div.
    • optionElement.appendChild(label);: Appends the label (containing the checkbox and text) to the div.
    • selectElement.appendChild(optionElement);: Appends the newly created option (with checkbox and text) to the selectElement (first element with class ‘select-options’) in the HTML document.

This code dynamically creates checkboxes for each option in the options array and appends them to the selectElement in the HTML document.

// Select the element with class 'select-options'
const selectElement = document.getElementsByClassName('select-options')[0];

// Define an array of options
const options = ['Option 1', 'Option 2', 'Option 3', 'Option 4', 'Option 5'];

// Loop through the options array to create checkboxes
options.forEach((option) => {
    // Create a new checkbox element
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox'; // Set the type to checkbox
    checkbox.value = option; // Set the value to the current option
    checkbox.id = option; // Set the id to the current option

    // Create a label for the checkbox
    const label = document.createElement('label');
    label.classList.add('options'); // Add 'options' class to the label
    label.appendChild(checkbox); // Append the checkbox to the label
    label.appendChild(document.createTextNode(option)); // Append the option text to the label

    // Create a container for the option
    const optionElement = document.createElement('div');
    optionElement.classList.add('options-container'); // Add 'options-container' class to the container
    optionElement.appendChild(label); // Append the label (checkbox and text) to the container

    // Append the option container to the select element
    selectElement.appendChild(optionElement);
});

Also read, The Future of Tech: 5 Must-Try No-Code Tools in 2023!

Track Number of Selection

This code essentially tracks the number of selected options by incrementing or decrementing the selected count based on the checkboxes clicked within elements with the class ‘options’. It updates the displayed count in an element with id ‘text’.

  • let selected = 0;: This line initializes a variable named ‘selected’ to 0. This variable will be used to keep track of the number of selected options.
  • let optionElement = document.getElementsByClassName(‘options’);: This line selects all elements with the class name ‘options’ and stores them in the variable ‘optionElement’.
  • The code then iterates through each ‘option’ element using a for…of loop:
    • for (let option of optionElement) { … }: This loop iterates over each ‘option’ element in the ‘optionElement’ collection.
    • option.addEventListener(‘click’, (e) => { … }: This line adds a click event listener to each ‘option’ element. When an option is clicked, the provided arrow function is executed.
    • Inside the event listener function:
      • if (e.target.checked === true) { selected += 1; }: If the clicked element (checkbox) is checked, increase the selected count by 1.
      • else if (e.target.checked === false) { selected -= 1; }: If the clicked element is unchecked, decrease the selected count by 1.
      • text.innerHTML = Selected (${selected});: Update the inner HTML of an element with id ‘text’ to display the current count of selected options.
// Initialize a variable to keep track of the number of selected options
let selected = 0;

// Select all elements with the class name 'options'
let optionElement = document.getElementsByClassName('options');

// Loop through each 'option' element
for (let option of optionElement) {
  // Add a click event listener to each 'option' element
  option.addEventListener('click', (e) => {
    // Check if the clicked checkbox is checked
    if (e.target.checked === true) {
      // If checked, increment the count of selected options
      selected += 1;
    } else if (e.target.checked === false) {
      // If unchecked, decrement the count of selected options
      selected -= 1;
    }
    // Update the text to display the count of selected options
    text.innerHTML = `Selected (${selected})`;
  });
}

Also read, Building a Linux Container using Namespaces

Demo

Checkbox inside Select Option using JavaScript

Also read, 8 Surprising Effects You Can Create with Text Animations in CSS

Final Words

I have demonstrated a simple way to incorporate a checkbox inside a select option using JavaScript. By following the steps outlined in this tutorial, you can dynamically add checkboxes to a select element, allowing users to select multiple options. This interactive feature enhances the user experience and provides a practical solution for scenarios where multiple selections are required.

To explore more articles on the latest trends in technology, continue reading our blog.

Table of Contents