PDA

View Full Version : Form validation form.length


braveheart09
10-05-2006, 04:29 AM
Greetings all!

I'm quite new to javascript so i may have some rather silly kind of questions... but anyway here's the problem...

I want to loop through all the elements in a form so as to check their values in order to validate the relevant fields, i thought i could get the number of form objects within the form using "formName.length." Then use a loop to go through all the form fields.

It seems formName.length is not working for me ... it's returning "undefined" or "0" values. How could i get the number of form objects within a certain form.

My code is as follows:
<script language="JavaScript">
window.moveTo(100,100);
window.resizeTo(300,460);
//window.locationbar.visible=false;
//window.menubar.visible=false;
//window.personalbar.visible=false;
//window.scrollbars.visible=false;
//window.statusbar.visible=false;
//window.toolbar.visible=false;
//window.resize=false;
//window.resizeable=no;

var elementNo;

elementNo = document.registrationForm.length;
//elementNo = document.registrationForm.txtFirstName.value;
var num;
num = document.forms[0].length;
var counter = 0;
var myMessage = "Please ensure that you have filled in the following fields:\n";
var myFieldsAlert = "";
var myAlertFlag="0";
function validate(){
//
alert("abc "+elementNo);
alert("abc "+num);
/**/
while(counter<elementNo){
//
if(registrationForm.elements[counter].value==""){
myFieldsAlert += "-"+registrationForm.elements[counter].id+"\n";
myAlertFlag="1";
}

if(registrationForm.optGenderM.value!="0" || registrationForm.optGenderF.value!="1"){
myFieldsAlert += "-Gender\n";
myAlertFlag="1";
}
counter++;
}
/**/
/**/
if(myAlertFlag=="1"){
alert(myMessaage+myFieldsAlert);
}
else{
registrationForm.submit();
}

myAlertFlag ="0";
/**/
return false;
}
</script>

Could someone please enlighten me on the issue at hand and propose a solution. (By the way the code is in a HTML page which is called up as a popup).

Any help would be greatly appreciated...

_Aerospace_Eng_
10-05-2006, 07:57 AM
You can get the elements length by doing
document.formName.elements.length;

braveheart09
10-07-2006, 11:23 PM
Thanks for your idea...
It does give the correct length, but the partial solution to my problem was that elementNo was being given a value of "undefined" or "0" because the form had not yet been created.

This is because the script is in the "head" of the document, and is executed before the form is actually created. Thus even the function would read the values as "undefined" or "0."

Putting
elementNo = document.registrationForm.length;

inside the function at the beginning solves the problem partially.

I'm still trying to get the whole "validate()" function to work ... it's still giving me a chaotic time...

_Aerospace_Eng_
10-07-2006, 11:30 PM
Put the stuff that accesses elements on the page in a function and call it using window.onload = someFunc