[Javascript] required entry field
Rodney Myers
rodney at aflyingstart.net
Sat Mar 29 04:05:57 CST 2003
To forestall queries about the use of the validation function in the
onSubmit event handler
Rodney Myers wrote:
> <form onSubmit=" isValid(this)" ....
>
> This allows the form object to be picked up as the parameter, which
> may be called anything but "form" is OK since as a parameter it is
> private within the function.
>
I was perhaps assuming too much in the previous posting tot hat quoted
above when I assumed that "everyone" would know that one passes the form
object to a validation function and how to do it. Sorry about that.
My last attempt is also misleading for those who really do not know how
to do this.
The use of an onSubmit handler allows the submission of the form to be
suppressed if the form validation is not OK.
Like everthing else this has to be done properly and regrettably
<form onSubmit="isValid(this)" ....
is just a gesture in the right direction rather than a full prescription.
The key thing is the return value of the validation function
So I would write in the form tag
<form onSubmit="return(isValid(this))" ....
Note the use of "this" which is a great puzzle to beginners.
It refers to the current object which is the form object because it is
in the context of the <form ...> tag
In a button it would refer to the button so this.form can be used to
access the form object - a very useful inversion of the usual object
hierarchy.
<input type="button" value="Check Form" onClick="isValid(this.form)"
Coming back to
<form onSubmit="return(isValid(this))" ....
The function could be
function isValid(form) {
var ret=true;
if(form.NeverBlank.value=='')
{
// return value is set false if any test is failed
form.NeverBlank.focus() ;ret=false;
}
// If ret is true the form will submit and if false then form will not
submit
return(ret);
}
And if using the button, which one notes was not a submit button, and so
not triggering any onSubmit event
Either the original form of the function, with no submit happening
function isValid(form) {
if(form.NeverBlank.value=='')
{
form.NeverBlank.focus() ;
}
}
or like this to submit the form if it passes validation
function isValid(form) {
var ret=true;
if(form.NeverBlank.value=='')
{
// return value is set false if any test is failed
form.NeverBlank.focus() ;ret=false;
}
if(ret){form.submit();}
}
Similar code and more can be found at this URL where I have parked my
course demos.
These were originally intended to be talked through in a live course,
but they show code and the effect of code so may help someone
http://www.aflyingstart.net/course_demos/
Rodney
--
PS. I have just bought a licence for Mike Chen's
BizAutomator. If you have to answer routine
email queries from your sites or mailings then
you need this as much as I do.
http://www.BizAutomator.com/rlbm51
More information about the Javascript
mailing list