Monday, July 30, 2012

Identify Text Element in a Form dynamically and perform Validation for the same.

The below script will search for all the text element with the name/id containing "_TallyCount".
and then validate if the text value is numeric.

Form Name : form1
Text Variable Naming Patter : "XXX_TallyCount"

var elem = document.getElementById('form1').elements;
        for(var i = 0; i < elem.length && elem[i].type=="text";  i++)
        {
   var elemType=elem[i].type;
   var elemName=elem[i].name;
   var elemValue=elem[i].value;
   if(elemType!='undefined' && elemType=="text" && elemName!='undefined' && elemName.indexOf("_TallyCount")!=-1)
   {
    if(((!isblank(elemValue)) && (!isNumeric(elemValue))) )
    {
     alert("Tally should be Numeric.\n");
     elem[i].focus();
     return false;
    }
   }
        }