I am finishing up my coding for a quiz app where questions are rendered one at a time and then finally the results table is rendered. Users can submit score and name to a scoreboard on another page. When the name input field is empty and the submit button is pressed, an error message is triggered. It was working fine if I did an alert
`else {
alert("Please input your your name before submitting your score");
}`
However, I don't want an alert. I want something a bit nicer so I did the following code. But every time button is submitted, the error is seen and then there ends up being multiple messages AND it doesn't go away even after the input field is populated. IDEALLY, I would like the error to render under the input field and not the submit button but I am fine, if this is not possible. Everything else works fine.
fname is the input field
renderHighScores has been declared elsewhere.
const handleResultsForm = (event) => {
event.preventDefault();
//get name from form
const fullName = document.getElementById("fname").value;
if (fullName) {
const yourScore = {
userName: fullName,
score: timerValue,
};
const highScores = readFromLocalStorage();
//push score object into LS
highScores.push(yourScore);
highScores.sort((a, b) => b.score - a.score);
writeToLocalStorage("highscores", highScores);
// render high scores page
renderHighScores();
} else {
//if name input is empty show error message
const nameInput = document.createElement("p");
nameInput.setAttribute("class", "confirm-name");
nameInput.setAttribute("id", "error-name");
nameInput.textContent = "Please enter your name";
const fullName = document.getElementById("submit-to-high-scores-button");
fullName.appendChild(nameInput);
}
};
// add submit event handler to form
submitScoresBtn.addEventListener("click", handleResultsForm);