Form clears after data validation finds an error

Mean MrMustard

Diamond Member
Jan 5, 2001
3,144
10
81
I built a form to collect data from users. When the Submit button is clicked a Javascript function runs to validate data. If the function finds an error, a message box pops up. If the user clicks OK the entire form clears and all the data has to be re-entered.

How do I stop the form from clearing?
 

Mean MrMustard

Diamond Member
Jan 5, 2001
3,144
10
81
Here's the main function:

function validateSendReport() {

if( document.contact.firstname.value=="" )
{
alert("Please provide a First Name.");
document.contact.firstname.focus();
return false;
}

if( document.contact.lastname.value=="" )
{
alert("Please provide a Last Name.");
lastname.focus();
return false;
}

if( !isValidEmailAddress(document.contact.email.value) )
{
alert("Please provide a valid Email Address.");
email.focus();
email.select();
return false;
}

if( document.contact.department.value=="" )
{
alert("Please provide a Department.");
department.focus();
return false;
}

if( document.contact.reportname.value=="" )
{
alert("Please provide a Report name.");
reportname.focus();
return false;
}

if( document.contact.dateneeded.value=="" )
{
alert("Please provide a Date Needed.");
dateneeded.focus();
return false;
}

sendReport();

alert( "The Report Request has been sent." );

return true;

}

It doesn't submit the form if it finds an error it just clears it if it does. If it doesn't find any errors it submits but doesn't clear.
 

Gunslinger08

Lifer
Nov 18, 2001
13,234
2
81
What language is the page written in? If asp.net, just use RequiredField or RegularExpression validation.
Otherwise, the crappy workaround: save the values in session variables when they click submit, do your validation, and have a function that loads the session variables into the form when the page loads, if they exist.
 

Gunslinger08

Lifer
Nov 18, 2001
13,234
2
81
Alternately, nest all of those if statements and negate them and put sendReport() with the alert inside the last if.

Like:
 

hellman69

Member
Feb 15, 2003
180
0
71
One other thing, make sure the form is calling the function like this: onSubmit="return validateSendReport();"

From the JS you provided, it wouldn't clear the fields unless the form is submitted.

Trevor