If you wanna go straight to the JavaScript way, the only thing you need to do is change your second select
to a multiselect (e.g. <select multiple>
), and then capture the selected values...
However, in order to have it more maintainable, as well as including the checkbox approach, you can create your own way to set them dinamicaly (and there are many ways to get there). Let's take a look:
var mealsByCategory = {
A: ["Soup", "Juice", "Tea", "Others"],
B: ["Soup", "Juice", "Water", "Others"],
C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
};
function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
var category = mealsByCategory[value][categoryId];
catOptions += "<label><input type='checkbox' name='categories' value='" + category + "' onclick='checkOptions()'>"
+ category + "</input></label>";
}
document.getElementById("checkboxes").innerHTML = catOptions;
}
}
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
function checkOptions() {
els = document.getElementsByName('categories');
var selectedChecks = "", qtChecks = 0;
for (i = 0; i < els.length; i++) {
if (els[i].checked) {
if (qtChecks > 0) selectedChecks += ", "
selectedChecks += els[i].value;
qtChecks++;
}
}
if(selectedChecks != "") {
document.getElementById("defaultCategory").innerText = selectedChecks;
} else {
document.getElementById("defaultCategory").innerText = "Select an option";
}
}
div.multiselect, select#meal, button {
margin: 5px;
}
.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;
}
<select name="meal" id="meal" onchange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select name="category" id="category">
<option id="defaultCategory">Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes"></div>
</div>
See that I just adapted your post to @vitfo solution's (see original post here), so don't forget to credit him too if it fits you.
Additionally, we have a bunch of other options to handle multiselects with checkboxes using plugins instead of the handy-way. A great example for this is the Multiple Select library that easily makes the same thing.