I have both a dropdown select option and some buttons both containing the same values.
When I select an option from my dropdown I want the button with the same value to add a class of selected and when I select another option from my dropdown I want it to remove the class of selected from the previous selection and add it to the new value.
For now I’ve only managed to get it to show a class of selected but it won’t remove this class from the previous option once I’ve selected a new one, does anyone know how I go about doing this please?
I only want to use vanilla JS for this, no jQuery please.
code below:
const btn = document.querySelectorAll(".btn-num");
const dropDown = document.querySelector('#dropdown-container .dropdown');
dropDown.addEventListener("change", function(){
btn.forEach(x => {
if (x.getAttribute('data-value') == this.value) {
x.classList.add('selected');
}
});
});
.btn-num.selected {
background-color: green;
color: #fff;
}
<div id="dropdown-container">
<select class="dropdown">
<option value="" selected="" disabled="">Numbers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="options">
<div class="btn-num" data-value="1">
1
</div>
<div class="btn-num" data-value="2">
2
</div>
<div class="btn-num" data-value="3">
3
</div>
<div class="btn-num" data-value="4">
4
</div>
</div>
5
Answers
You forgot to remove class. Use
x.classList.remove()
If you wanted to remove class only from the currently
.selected
item us can us?.
syntax is used to check if element.selected
exists and remove the class only form the specific element:
To remove the
selected
class you just need to addx.classList.remove('selected');
right before your conditional check.I’m not quite sure, but I think this piece of code could work, where the "selected" class is being removed from all buttons using x.classList.remove(‘selected’). Then adding "selected" class only to button whos ‘data-value’ attr. matches the newly selected option in the dropdown, using the ‘x.classList.add(‘selected’) instead of the remove, of course:
This should help you get the desired functionality where only one button has the "selected" class at any given time, and it corresponds to the currently selected option in the dropdown.
Hope this helps! 🙂
It’s fairly simple. Others explained it already. I wrote it slightly differently, but it doesn’t make a difference. It’s really just adding the
classList.remove('selected')
method. Maybe my version will help anyway.for shorter code use
classList.toggle()
method