SO-47692625
by David Thomas
HTML
<input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>
<select name="services">
<optgroup label="Application">
<!-- Shown -->
<option value="Office">Office</option>
<option value="SAP">SAP</option>
</optgroup>
<optgroup label="Infrastructure Service">
<!-- Hidden -->
<option value="Router">Router</option>
<option value="Switch">Switch</option>
</optgroup>
<optgroup label="Platform">
<!-- Hidden -->
<option value="Server">Server</option>
<option value="Client">Client</option>
</optgroup>
<optgroup label="Software">
<!-- Shown -->
<option value="Word">Word</option>
<option value="Excel">Excel</option>
</optgroup>
</select>
CSS
label::after {
content: '';
display: block;
}
JavaScript
function toggleIfChecked() {
let el = this,
label = el.labels.length ? el.labels[0] : el.nextElementSibling,
text = label.textContent.trim(),
select = document.querySelector('select[name=services]');
Array.from(
select.querySelectorAll('optgroup[label="' + text + '"]')
).forEach(
optgroup => optgroup.style.display = el.checked ? 'block' : 'none'
);
}
let changeEvent = new Event('change');
Array.from(
document.querySelectorAll('input[type=checkbox]')
).forEach(
input => {
input.addEventListener('change', toggleIfChecked);
input.dispatchEvent(changeEvent);
}
);