// Get the first select element.
var items = document.querySelector('#items');
// Get the second select element.
var itemsChild = document.querySelector('#itemchild');
// Create a list with all the values I could use in the second
// select element as option tags.
var itemsChildData = [
{
value: 0,
group: "SHOW",
text: '-- Select --'
},
{
value: 'green',
group: "xxxxx",
text: 'green'
},
{
value: 'yellow',
group: "xxxxxx",
text: 'yellow'
},
{
value: 'blue',
group: "xxxxxx",
text: 'blue'
},
{
value: 'red',
group: "xxxxx",
text: 'red'
}
];
// Listen for the change event in the first select element.
items.addEventListener(
'change',
function(event) {
// Get the selected value from the first select element
var value = event.target.value;
// Get the last letter from the selected value
var lastLetter = value.split('').pop();
// Filter the list of the possible options for the second
// select element
var filteredOptions = itemsChildData.filter(
function(item) {
// If the last character is s
if ( 's' === lastLetter ) {
// Return true, if the value is red or 0
return -1 !== ['red', 0].indexOf( item.value );
}
// If the last character it is not s, return always true
return true;
}
);
// Get all the option tags from the second select element.
var options = itemsChild.querySelectorAll('option');
// If we found options
if(options){
// Itterate over the found options
options.forEach(
function(opt){
// And remove them from the select element.
opt.parentElement.removeChild(opt);
}
);
}
// Finally, iterate over the filtered options
filteredOptions.forEach(
function(newOption) {
// Create a new option element
var option = document.createElement('option');
// Assign the value
option.value = newOption.value;
// Assign the text
option.innerText = newOption.text;
// Assign the data-group
option.dataset.group = newOption.group;
// And append the new option to the second select element.
itemsChild.appendChild(option);
}
);
}
);
<select class=form-control name="items" id="items" data-child="itemschild">
<option selected disabled>Items</option>
<option value="Vips">Vips</option>
<option value="Superstars">superstars</option>
<option value="chief">chief</option>
<option value="employer">employer</option>
</select>
<select class=form-control name="itemschild" id="itemchild">
<option data-group='SHOW' value='0'>-- Select --</option>
<option data-group="xxxxx" value="green">green</option>
<option data-group="xxxxxx" value="yellow">yellow</option>
<option data-group="xxxxxx" value="blue">blue</option>
<option data-group="xxxxx" value="red">red</option>
</select>