Click to See Complete Forum and Search --> : Getting Form elements in JavaScript
bharadwajrv
September 9th, 2002, 05:05 AM
Hi,
i wanted to validate the Form elements using Java Script here is my code but it not working validating...
In script
function ValidateNewPost()
{
if (document.NewPost.txtSubject.Length ==0 )
{
alert("Enter the Subject");
return false;
}
}
in body
<form OnSubmit="ValidateNewPost();" name=NewPost>
<input type=text name=txtSubject>
..
</form>
thanks in adv.
Venu Bharadwaj
Zvona
September 9th, 2002, 07:01 AM
function ValidateNewPost()
{
if (document.NewPost.txtSubject.value.length ==0)
{
alert("Enter the Subject");
return false;
}
}
in body
<form onsubmit="return ValidateNewPost();" name="NewPost">
<input type="text" name="txtSubject">
</form>
websmith99
October 7th, 2002, 05:11 PM
A few points:
If your form elements have dynamic names (filled in server side) and there is the possibility that a name could contain spaces, then it is best to use the forms[] and elements[] collections when using the DOM to reference them.
Example in valid XHTML:
<input type="text" name="<%= textField1 %>" />
evaluates to:
<input type="text" name="my textfield" />
Now using
document.NewPost.my textfield.value.length
will result in a JavaScript error, as the DOM reference is truncated at the space between the "y" and the "t" in "my textfield". The solution as mentioned above would be to do this:
document.forms['NewPost'].elements['my textfield'].value.length
Secondly, if the condition in ValidateNewPost() fails, you should explicitly return true, as the onsubmit event handler expects a return value from the function and not all browsers would return a value implicitly in that case:
if (document.forms['NewPost'].elements['my textfield'].value.length==0) {
alert("Enter the Subject");
return false;
} else {
return true;
}
:cool:
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.