Design comparison
Solution retrospective
Any feedback on any part I could have handled better or more efficiently is always valued an appreciated.
Thanks in advance 👏🏾
Community feedback
- @LuizaUszackiPosted over 2 years ago
Nice job completing the challenge. I hope to help you with some advice about your code.
- If you click on more than one number, all clicked numbers will be selected instead of just the last one. So, to avoid it, you could remove the selected class from your buttons when selecting a button (of course, it's not the only way to solve it, you could also save the first selected button and remove the class just from it). Then, it will have just one button becoming gray, even if you click on more than one button.
Like that:
rateBtns.forEach((btn) => { btn.addEventListener("click", () => { removeSelected(); btn.classList.toggle("selected"); // In this way, toggle will always add the class yourRate = btn.innerHTML; }); }); function removeSelected() { rateBtns.forEach(btn => { btn.classList.remove('selected'); }) }
- I believe you won't need the second advice if you follow the first one because you will always have at least one number selected after selecting the first one, but I will tell you anyway, just in case...
The way you are doing, if you select and deselect one or more buttons and try to submit it, it'll still submit even without any button selected. To solve it, instead of using
yourRate != ""
, you could check whether any of the buttons in rateBtns has the class selected or not.
Hope it helps you.
Marked as helpful0@LeskimPosted over 2 years ago@LuizaUszacki implemented the
removeSelected
function but got stuck on checking if if the btn has the selected class before submitting ... still usingyourRate != ""
0@LuizaUszackiPosted over 2 years ago@Leskim I think the problem might be because you didn't initialize
yourRate
as "", it'sundefined
now andundefined
is different from "". That why it shows the "Thank you" page.So, I believe if you initialize it as "", it will work, but if you want to check the class anyway, you could do it:
function hasSelected(arr) { let selectIndex = -1 arr.forEach((el, index) => { if (el.classList.contains('selected')) { selectIndex = index } }) return selectIndex }
And then test with:
if (hasSelected(rateBtns) != -1) { ratingSection.style.display = "none"; thanksSection.style.display = "block"; displayRate.textContent = yourRate; }
I'm not sure it's the best way to do it, but I think it works. It's almost the same as what I did.
Marked as helpful0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord