2

How to multiselect a dynamically populated dropdown based on another dropdown value selection?

I have 2 dropdowns on the page. The 2nd dropdown will be empty on the first instance. When you select the values in 1st dropdown and, based on that values, the 2nd dropdown will be available. Now I want 2nd dropdown as a Multi-select.

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]) {
                catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
            }
            document.getElementById("category").innerHTML = catOptions;
        }
    }
<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>
<select name="category" id="category">
    <option value="" disabled selected>Select</option>
</select>

Does anyone has any idea of how can I get this?

HPierce
  • 7,249
  • 7
  • 33
  • 49
ravi
  • 33
  • 1
  • 5

2 Answers2

1

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.

Community
  • 1
  • 1
diogo
  • 3,769
  • 1
  • 24
  • 30
  • thanks for your valuable answer...its working fine..but instead of check options button i want to displayed in the top directly..how many are selected or selected names should be displayed..thanks so much – ravi Nov 06 '16 at 17:19
  • What do you mean about "display in the top directly"? Into a `div` at the top of the page or as the text of the select (I mean, instead of the "select an option")? – diogo Nov 06 '16 at 17:33
  • i mean in the place of "select an option" – ravi Nov 06 '16 at 17:35
  • It's simple: just add an `onClick` to call a function every time the options are checked (or unchecked), and then, loop the checkboxes looking for the cheked options, concatenating their texts and showing it at the main label of the select. Same thing is possible if you want to show the number of items selected. Code is now adjusted for it. – diogo Nov 06 '16 at 18:14
0

You can use a jquery plugin that provides this functionality, instead of developing it yourself: https://github.com/dnasir/jquery-cascading-dropdown

zooglash
  • 1,750
  • 13
  • 16
  • thanks for your reply...but i want 2nd dropdown should be multiselect...how to multiselect the dropdown values using checkbox after populating the data – ravi Nov 06 '16 at 08:24