whitewolf13 whitewolf13 - 7 months ago 20
HTML Question

Javascript validation - Error message only flashes for a second

I have this simple HTML project that validates an empty text and radiobutton field. The error is being displayed if one of the fields are empty, but the error message only flashes on the screen for a second, before disappearing again. Why is this happening?

Here's my HTML code

<form id="food_form">
<p>
<label>Your Name:
<input type="text" id="user_name" name="user_name">
</label>
<span id="error_user_name" class="error"></span>
</p>
<p>
Favorite Food?
<span id="error_radiobutton" class="error"></span><br>
<label><input type="radio" name="radiobutton" value="pizza">Pizza</label><br>
<label><input type="radio" name="radiobutton" value="burger">Burger</label><br>
<label><input type="radio" name="radiobutton" value="spaghetti">Spaghetti</label><br>
</p>

<input type="submit" value="Submit">




And then my Javascript code

<script>

document.getElementById("food_form").onsubmit = validateForm;

function validateForm() {

var validName = validateTextBox("user_name", "error_user_name"),
validRadiobutton = validateRadioButton();

}

function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId);

if (text === "") {
errorSpan.innerHTML = "* please input your name";
}


}

function validateRadioButton() {

var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false,
i;

errorSpan.innerHTML = "";

for (i = 0; i < radiobutton.length; i++) {

if (radiobutton[i].checked) {
isChecked = true;
break;
}

}

if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";

}

}




Your response would be kindly appreciated.

Answer

Your function validateForm sets the error message but then you call validateRadioButton() which sets again errorSpan.innerHTML = "";. That is the reason of the "flash"