@elaineleung
Posted
Hey Joshua, I just had a look at your code, and I do agree, the if/else statements are somewhat verbose. The bigger problem, however, is that it doesn't seem like the rating is working the way it should, most likely because buttons don't have a click
or clicked
attribute. From my end at least, any number I choose would end up with a 5 rating.
Anyway, I'm going to make a few suggestions that you can try out:
(1) Group your five rating-el
buttons together:
const ratingEls = document.querySelectorAll('.rating-el');
The good thing is you're using buttons and not plain divs, which means there's info such as value that you can take from the buttons. Once you group them together, you can iterate/loop through them and not need to write out five separate variables for each one.
(2) Add an event listener for the buttons to observe which button is clicked so that you can track the value. To do that, I'll create a variable called selected
set to null and also use a forEach()
to add an event listener to the ratingEls
button group created earlier; the forEach()
would just loop through the group so there's no need to write out five different event listeners. The event listener would contain a function that says, if this button is clicked, set selected
to the value of the button.
let selected = null
ratingEls.forEach((btn) => {
btn.addEventListener('click', () => selected = btn.value);
});
(3) Replace the if/else statements: Using the information from the selected
variable, we can then rewrite the valueSelection()
function like this with the help of template literals (as in, ${}
):
function valueSelection() {
selectionEl.textContent = `You selected ${selected} out of 5`;
}
The whole thing would look something like this:
const ratingEls = document.querySelectorAll('.rating-el');
let selected = null;
ratingEls.forEach((btn) => {
btn.addEventListener('click', () => selected = btn.value);
});
submitEl.addEventListener('click', function () {
if (selected) { // this prevents the screen from changing if nothing is selected
ratingWrapper.style.display = 'none';
ratingWrapper2.style.display = 'grid';
valueSelection();
}
});
function valueSelection() {
selectionEl.textContent = `You selected ${selected} out of 5`;
}
I know this might be beyond your knowledge right now, but I think you can at least use some of this as reference and then do some more research on your own. Anyway, hope this is of use to you!