Tuesday, April 8, 2008

JAvaScript function to Count no Of Specific Fields( Like TextBoxes)

Sometimes, you create textboxes or othe form fields dynamically using some server side scripting language. Then you may need to count the number of fields using some JAvaScript. The following javascript function will return the no of specific fields of a form passed in parameters:

It has two parameters:
1- formName:- It is the attribute name of the form
2- inputtype:- Type of Field as a String argument.

For Example if you would like to count the number of textBoxes in the HTML form, the following call will work.

var noOfTextBoxes = countElement(formName,"text");

Similarly, to count no of buttons in HTML form, call the function like:

var noOfTextBoxes = countElement(formName,"button");


Here is the implementation of JavaScript function:

function countElement(formName,inputtype)
{
var count =0;
for(i=0; i < formName.elements.length ; i++ )
{
if(formName.elements[i].type==inputtype)
{
//
alert(formName.elements[i].value);
count=count+1;

}
}
return count;
}







View Sabah u Din Irfan's profile on LinkedIn

No comments: