Saturday, May 24, 2008

How do i pick up all the fields of a form with javascript?

I have devised a simple way of picking up all the datas in my form for either
client side validation or for packaging and sending it to the server via Ajax
I will illustrate this with a basic form with two input box and two select box
the form structure first

<form method='post' action=''>
<table width='400'align='center'>
<tbody>
<tr>
<td>Firstname</td>
<td><input type='text' id='csFname' name='ssFname'>/</td>
</tr>
<tr>
<td>Lastname</td>
<td><input type='text' id='csLname' name='ssLname'>/</td>
</tr>
<tr>
<td>Age</td>
<td><select id='csAge' name='ssAge'>
< option value=''>Select one< option >
< option value='20'>20< option >
< option value='30'>30< option >
< /select >
</td>
</tr>
<tr>
<td>Sex</td>
<td><select id='csSex' name='ssSex'>
< option value=''>Select one< option >
< option value='Male'>Male< option >
< option value='Female'>Female< option >
< /select >
</td>
</tr>
< tr > < td colspan='2'> < input type='button' value='Submit'/>
</ td > < /tr >
</tbody>
</table>
</form>
All that is needed now is to write the script that will pick up all the data
to do this i always use javascript objects method of coding
or what is called the singleton pattern

var handleForm={
errorCode:0,
dataToServer:null,
errorMessage:null,
/**
*A function to start up the function when the page loads
*/
initDoc:function()
{
if(!document.getElementById && !document.createTextNode)
{return;}
},
/**
* A validating function validates all the form entries
* Node this is a generic validator that determines
* the type of object to be validated and then calls
* the appropriate method to do the validating
*/
validate:function(vtype,data)
{
if(!vtype)
{return}
var self=handleForm;
switch(vtype)
{
case'name':
self.validateName(errorPlace,data);
break;
case'age':
self.validateAge(errorPlace,data);
break;
case'sex':
self.validateSex(errorPlace,data);
break;
}
return;
},
/**
* Define the specific validating scheme for
* all the entries in the validate function
* for instance the name entries validator
* would look like this
*/
validateName:function(errorDiv,dataValue)
{
var self=handleForm;

var exp=%^[a-zA-Z]{3,}$%;
if(!dataValue.match(exp))
{
return self.discardValue(errorDiv,'Invalid name') ;
}else
{return self.acceptValue(errorDiv);}
},
/**
* The discardValue and acceptValue function are
*Helper function that informs the user when something
*goes wrong and when some thing goes write
*/
discardValue:function(errorDiv,errorMsg)
{
var self=handleForm; //references the class itself
//get the place you display error, ususally in a div
var epanel=document.getElementById(errorDiv);
epanel.innerHTML='';

//set the errorCode to a number greater than 0, this tells your script
//stop any process when there is an error somewhere
self.errorCode=434;
epanel.innerHTML=errorMsg;
return;
},
/**
* This is fired when the is a correct value or acceptable value
* it set the errorCode back to 0 and clears the error display place
*/
acceptValue:function(errorDiv)
{
var self=handleForm;
var epanel=document.getElementById(errorDiv);
epanel.innerHTML='';
self.errorCode=0;
return;
},
/**
* We define the function that is called
* when the submit button is clicked
*note that this does the picking,validating and packaging
* of the data for serverside process
*/
getData:function()
{
//define and object array
var ddata=['csFirstname':null,
'csLastname':null,
'csAge':null,
'csSex':null
];

//get all the input object in the form
var inputs=document.getElementsByTagName('input');

//get all the select object in the form
var selects=document.getElementsByTagName('select');

//loop through all the input object validating and putting then into
// the object array ddata

var self=handleForm;

for(var i=0;i<inputs.length;i++)
{
var e=inputs[i];
if(e.type=='text' && e.value.length>0)
{
//here we determine the type of object it is so
// that we can validate it
//remove the prefix cs from the id and pass it to the validating
// function
var thetarget=e.id.substring(2,e.id.length);
self.validate(thetarget,e.value);

//break out of the loop if the is a problem
if(self.errorCode>0)
{
break;
}else
{
// add the value to the array object
ddata[e.id]=e.value;
}
}else
{//fields are empty
alert('Please fill out the form');
}
}
//that does it for all the input fields
// now for the select fields it is still the same loop but with slight difference

for(var k=0;k<selects.length;k++)
{
var d=selects[k];
if(d.selectedIndex>0)
{
//pick out each for validation
var thetarget=d.id.substring(2,d.id.length);
self.validate(thetarget,d.options[d.selectedIndex].value);
if(self.errorCode>0)
{
//a problem break;
}else
{
//add to the object array
ddata[d.id]=d.options[d.selectedIndex].value;
}
}else
{// an empty select box
alert('Please select something');
break;
}
}
if(self.errorCode>0)
{
// the was a problem stop the processing
return;
}
self.dataToServer=ddata;
var formattedData=self.encodeData();
//here goes the Ajax call to the server;
},
/**
* If all the validating went fine without errorCode going beyond 0
* We then encode all the data in the object array for Ajax transmission
* The function bellow does just that
*/
encodeData:function()
{
var self=handleForm;
var str='ajax=1';
var items=self.dataToServer;
for(var item in items)
{
str+='&'+ encodeURIComponent(item)+'='+ encodeURIComponent(items[item]);
}
return str;
}
}

1 comment:

Juwon Daniel said...

this is really a good bunch of codes,,, please i will like to contact you for us to have a chat, it might not be online, cos i might not be online for some time.. thank you..