whitewolf13 whitewolf13 - 9 months ago 36
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">
<label>Your Name:
<input type="text" id="user_name" name="user_name">
<span id="error_user_name" class="error"></span>
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>

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

And then my Javascript code


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,

errorSpan.innerHTML = "";

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

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


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



Your response would be kindly appreciated.


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