Hello,
I’m using plain JavaScript to show only the three shirt options (“Cornflower Blue, Dark Slate Grey, and Gold”) when Theme - JS Puns option is selected in the first select option and same for Theme - I Love JS which will show ('Tomato, Steel Blue and Dim Grey).
But when I select the Theme - I Love JS the “Cornflower Blue” appears in the dropdown with the Theme - I Love JS options. The image below shows what I mean.
Below is the markup:
HTML
<fieldset class="shirt">
<div>
<label for="design">Design:</label>
<select id="design" name="user_design">
<option>Select Theme</option>
<option value="js puns">Theme - JS Puns</option>
<option value="heart js">Theme - I ♥ JS</option>
</select>
</div>
<div id="colors-js-puns" class="categories">
<label for="color">Color:</label>
<select id="color">
<option value="cornflowerblue">Cornflower Blue (JS Puns shirt only)</option>
<option value="darkslategrey">Dark Slate Grey (JS Puns shirt only)</option>
<option value="gold">Gold (JS Puns shirt only)</option>
<option value="tomato">Tomato (I ♥ JS shirt only)</option>
<option value="steelblue">Steel Blue (I ♥ JS shirt only)</option>
<option value="dimgrey">Dim Grey (I ♥ JS shirt only)</option>
</select>
</div>
</fieldset>
JAVASCRIPT
design.addEventListener('change', (e) => {
const color = document.getElementById('color'); //gets the select element with id "#color"
if (e.target.value == 'js puns') {
for (let i = 0; i < color.children.length; i++) {
if (color.children[i].index <=2) { //if the option index is less than or equal to 2
color.children[i].classList.add('active');
} else {
color.children[i].classList.remove('active');
color.children[i].classList.add('none');
}
}
}
if (e.target.value == 'heart js') {
for (let i = 0; i < color.children.length; i++) {
if (color.children[i].index >= 3) { //if the option index is greater than or equal to 3
color.children[i].classList.add('active');
} else {
color.children[i].classList.remove('active');
color.children[i].classList.add('none');
}
}
}
});
CSS
.none {
display: none;
}
.active {
display: block;
}