To add checkboxes inside select options with JavaScript, we can wrap our select drop down in a div and then add a div below the select element to show the drop-down choices.
For instance, we can write the following HTML:
<form>
<div class="multiselect">
<div class="selectBox">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" />First checkbox</label>
<label for="two">
<input type="checkbox" id="two" />Second checkbox</label>
<label for="three">
<input type="checkbox" id="three" />Third checkbox</label>
</div>
</div>
</form>
We add the select
element with the div with ID checkboxes
with the choices.
The input with type checkbox
are the checkboxes.
Then we can add the following CSS to make the choices look like they’re part of the drop-down:
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
To do that, we div with ID overSelect
absolute.
And we make the div with ID selectBox
have relative position.
Also, we make the div with ID checkboxes
hidden by setting the display
property to none
.
Finally, we add the following JavaScript code to toggle the div with ID checkboxes
on and off:
let expanded = false;
const showCheckboxes = () => {
const checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
const selectBox = document.querySelector('.selectBox')
selectBox.addEventListener('click', showCheckboxes)
We add the expanded
variable to track the display state of the checkbox.
And we get the div with ID checkboxes
with document.getElementById
.
If expanded
is false
, then we set display
to 'block'
.
Otherwise, we set display
to 'none'
.
We also update expanded
accordingly in each case.
Finally, we get the div with class selectBox
with document.querySelector
, call addEventListener
with 'click'
to add a click listener to it, and use showCheckboxes
as the click listener.
Now when we click on the select element, we should see the drop-down with the checkboxes that we created.