PDA

View Full Version : Validating for empty fields before printing


FayeC
02-14-2008, 03:31 PM
I have a form that needs to be validated and if required fields are empty it should show a warning and focus back on the empty field.
I have that part figured out.
The issue is to add to the code that only after the required fields are filled it should send the page to be printed.
When I add the else statement to window.print() everything fails and the form doesn't even validate anymore. Without the else statment it validades fine.

I have the following:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false;}
else {return true}
}
}



function validate_form(thisform)
{
with (thisform)
{
if (validate_required(field1,"You need to fill all required fields before this form can be printed.")==false)
{field1.focus();return false;}
if (validate_required(field2,"You need to fill all required fields before this form can be printed.")==false)
{field2.focus();return false;}
if (validate_required(field3,"You need to fill all required fields before this form can be printed.")==false)
{field3.focus();return false;}
else {window.print}
}
}

Any help is appreciated.

FayeC

Kor
02-14-2008, 04:40 PM
This is the reason for the with() method should never be used. The way you have coded, window.print() (by the way, you forgot the method's brackets) became thisform.window.print(), which is nonsense. And you don't need two functions, one is enough:

<script type="text/javascript">
function validate_form(f){
var names=['field1','field2','field3'], n, i=0;
while(n=names[i++]){
if(f[n].value==null||f[n].value==''){
alert('You need to fill all required fields before this form can be printed.');
return;
}
}
window.print();
}
</script>

FayeC
02-14-2008, 05:17 PM
Hi,

Thank you for your fast reply :)
I actually got that code from a Javascript online tutorial.
My questions now are how to insert the focus part on your code. It works fine but doesn't focus on the first field that returned a false.
And how to stop the form from refreshing on submit.

FayeC

Kor
02-14-2008, 08:09 PM
1.

<script type="text/javascript">
function validate_form(f){
var names=['field1','field2','field3'], n, i=0;
while(n=names[i++]){
if(f[n].value==null||f[n].value==''){
alert('You need to fill all required fields before this form can be printed.');
f[n].focus();
return;
}
}
window.print();
}
</script>

2. it depends on your action of the submit and on what thet CGI (server application) is instructed to do.

j3n0vacHiLd
02-15-2008, 05:47 PM
If your having a button to click when the form is filled out and you dont want this button to also refresh the form (submit it) then check the code that corresponds with your button. If it says something like..

<input type="submit" value="Print Form" id="btnPrint">

Then try changing the type to button:

<input type="button" value="Print Form" id="btnPrint">