Show/hide Select Boxes Depending On The Previous Selection – multiSelect.js

Category: Form , Javascript | December 12, 2019
Author:carlosEdua
Views Total:1,766 views
Official Page:Go to website
Last Update:December 12, 2019
License:MIT

Preview:

Show/hide Select Boxes Depending On The Previous Selection – multiSelect.js

Description:

multiSelect.js is a simple dependent dropdown plugin that dynamically shows/hides child select elements depending on the previous selection in the parent select element.

It also allows you to send the values you selected in multiple select elements to the server.

How to use it:

1. Add the multiSelect attribute to the form element.

<form multiSelect onsubmit="return false">
  ...
</form>

2. Insert parent & child select elements into the form as follows:

<div visibleId="select1">
  <select name="mySelect1">
    <option value="nothing">please select a option</option>
    <option value="v1" makeVisible="sub-select1">sub select 1</option>
    <option value="v2" makeVisible="sub-select2">sub select 2</option>
    <option value="v3" makeVisible="a-sub-div">sub div</option>
  </select>
</div>
<div parent="select1">
  <!-- el valor de visibleId debe ser el valor del makeVisible correspondiente -->
  <div visibleId="sub-select1">
    <select name="subSelect1">
      <option value="nothing">select an option</option>
      <option value="subSelect1-value-1">sub select 1 option</option>
      <option value="subSelect1-value-2">other sub select 1 option</option>
    </select>
  </div>
  <div visibleId="sub-select2">
    <select name="subSelect2">
      <option value="nothing">select an option</option>
      <option value="subSelect2-value-1">sub select 2 option</option>
      <option value="subSelect2-value-2">other sub select 2 option</option>
    </select>
  </div>
</div>

3. Initialize the plugin.

const multi = new MultiSelect({
      pleaseSelectOptionValue: 'nothingHere' 
});

4. Submit the form and send the selected values to the server.

// get the <select> values
const values = multi.getJson(false);
console.log(values);
// validate
if(multi.simpleValidate()){
  // make something
}else{
  //make something
}

5. Hide the selects on the first load.

[multiSelect] [parent]{
  display: none;
}

You Might Be Interested In:


Leave a Reply