This is a very cut-down version to visualize what I'd like to do.
My HTML
<p >Please select a number.</p>
<div >
<button >1</button>
<button >2</button>
<button >3</button>
<button >4</button>
<button >5</button>
</div>
My JS
let allBtns = document.querySelectorAll(".rating");
allBtns.forEach((option) => {
option.addEventListener("click", function () {
option.style.backgroundColor = "orange";
});
});
Essentially, I want a user to be able to click on only a single rating (1 thru 5) that will eventually be used to update a string.
The main problem I'd like to tackle right now is being able to select one value, pick another one, and have the previously chosen value be deselected. I was able to find a method using radios, and checkboxes will work, but I also want to keep the button style because that's how it's supposed to be displayed.
Is this possible with a normal button element?
CodePudding user response:
let allBtns = document.querySelectorAll(".rating");
allBtns.forEach((option) => {
option.addEventListener("click", function (event) {
allBtns.forEach(el => {
el.classList.remove('active');
});
event.currentTarget.classList.add('active');
});
});
.rating.active {
background-color: orange;
}
<p >Please select a number.</p>
<div >
<button role="radio" >1</button>
<button role="radio" >2</button>
<button role="radio" >3</button>
<button role="radio" >4</button>
<button role="radio" >5</button>
</div>
Identifies the currently selected button element with .active
When the button is selected, remove the .active from all Button Elements and insert the .active into the newly selected button.
CodePudding user response:
You should memoize last button, then change it back on next click, like this:
let allBtns = document.querySelectorAll(".rating");
let lastBtn;
allBtns.forEach((option) => {
option.addEventListener("click", function () {
lastBtn && (lastBtn.style.backgroundColor = null);
(lastBtn = option).style.backgroundColor = "orange";
});
});
<p >Please select a number.</p>
<div >
<button >1</button>
<button >2</button>
<button >3</button>
<button >4</button>
<button >5</button>
</div>