JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<select name="filter" id="filter-dropdown" data-update="#target-dropdown">
<option value="">Select one</option>
<option value="value-1">Test 1</option>
<option value="value-2">Test 2</option>
</select>
<select name="dropdown" id="target-dropdown">
<option value="target-1" data-applies="value-1,value-2">Targets: 1, 2</option>
<option value="target-2" data-applies="value-1">Targets: 1</option>
<option value="target-3" data-applies="value-2">Targets: 2</option>
</select>
JavaScript
console.clear();
var filterDropdown = function(elem){
var _this = this;
// Locate elem and attributes
if(!elem || !elem.getAttribute('data-update')){ return false; }
this.elem = elem;
// Locate target
this.target = document.querySelector(this.elem.getAttribute('data-update'));
if(!this.target){ return false; }
// Store option nodes
this.target_options = [];
Array.prototype.forEach.call(this.target.children, function(opt, i, a){
_this.target_options[_this.target_options.length] = opt;
});
// Clear
this.clearFilter(true);
// Bind change event
this.elem.addEventListener('change', function(){
_this.updateFilter.apply(_this);
});
};
filterDropdown.prototype.clearFilter = function(append_empty){
// Clear filter options
this.target.options.length = 0;
// Add empty option
if(append_empty){
var empty_opt = document.createElement('option');
empty_opt.setAttribute('disabled', true);
empty_opt.setAttribute('selected', true);
this.target.appendChild(empty_opt);
}
};
filterDropdown.prototype.updateFilter = function(){
var _this = this;
// Get value
var val = this.elem.options[this.elem.selectedIndex].value;
if(val){
this.clearFilter();
// Loop stored filters
Array.prototype.forEach.call(this.target_options, function(opt){
// Locate "applies to" list
var applies = opt.getAttribute('data-applies');
if(applies){
applies = applies.split(',');
if(applies.indexOf(val) !== -1){
// Append if apply match
_this.target.appendChild(opt);
}
}
});
}else{
// Empty if no match
this.clearFilter(true);
}
};
//////////
// DEMO //
//////////
new filterDropdown(document.getElementById('filter-dropdown'));