Hi all,

I have a html page with html form input boxes in it. What I want to do is validate these input boxes with javascript. I have a span element(error message) next to the text boxes which will only be visible when the user submits the form without entering anything in the textbox. I have been able to achieve this, but when I test the page the error message will appear then disappear straight away (flashes). How can I make the message stay on the page until the user resubmits the form?

<form action="#" method="get" onsubmit="return validate()" name="signup">
<p class="left">First name: </p> <input type="text" name="firstname"/> <span id="error">Enter your first name!</span> <br/>
function validate() {
	firstname();
}

function firstname() {

	var x=document.forms["signup"]["firstname"].value;
	if (x==null || x=="") {
		document.getElementById("error").style.visibility = "visible"; 
		document.signup.firstname.focus();
	}

}

you have to return false when there is an error. Since you are NOT doing that, the form gets submitted and quickly reloaded (hence the "flash"). Try:

function validate() {
	var ok=true;
	ok=ok && firstname();
	ok=ok && lastname();
return ok;
}

function firstname() {

	var x=document.forms["signup"]["firstname"].value;
	if (x==null || x=="") {
		document.getElementById("error").style.visibility = "visible"; 
		document.signup.firstname.focus();
		return false;
	}
return true;
}
function lastname() {

	var x=document.forms["signup"]["lastname"].value;
	if (x==null || x=="") {
		document.getElementById("error").style.visibility = "visible"; 
		document.signup.lastname.focus();
		return false;
	}
return true;
}

Thanks, good solution :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.