Design comparison
Solution retrospective
If a user doesn't choose any value 1-5 and still hits submit, is there a code to prevent them from doing so?
I tried to write javascript code where it would be impossible for a user to hit submit button if they don't choose any value 1 - 5 to give rating.
In that case, they wouldn't be able to proceed even if they pressed submit, because there would be an alert displayed, warning them to first choose a value between 1 and 5.
I know there should be an if statement and compare rating to the one we get from buttons as input, but I couldn't complete the code. The furthest I got was to be able to display this alert, but it was then displayed each time I pressed submit, instead of only when I didn't choose any value.
Community feedback
- @RalfiSlaskPosted over 1 year ago
You should probably make use of a boolean variable.
- First declare lets say buttonPressed = false.
- Change it to true in your click event listener for the buttons.
- Create an if else statement in the click event for the submit button.
- In the if-statement write if(buttonPressed === true) or if(buttonPressed) which is the same and in the if block write out your code.
- In the else statement you can either apply an alert (this is not very pretty though) or attach lets say a red error message on the container that lets the user know they need to press one of the buttons.
Good Luck!
2@d8701aPosted over 1 year ago@RalfiSlask This was such an elegant solution! I implemented it right away, and it worked like a charm. I agree displaying a simple alert message looks inelegant (and rather aggressive indeed), but for my demo purposes it served.
I can't believe I completely forgot about the power of boolean values.
Thank you so much for this, it was short, simple and efficient!
0
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