Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need explanation of how script is working

Status
Not open for further replies.

evergrean100

Technical User
Dec 1, 2006
115
US
This below validates and makes sure all radio buttons are populated on web page. I dont understand how it works and was hoping to get explanation:

Code:
function val(){
var myForm=document.getElementById("myForm");
var myFields=myForm.getElementsByTagName("input");
var results={};
var resultString="";
	
for (var i=0;i<myFields.length;i++) {
if(myFields[i].type=="radio"){
//The next two lines are the main areas I need expanation because not sure why it checking "undefined" and then naming it 0? 
if(results[myFields[i].name]==undefined) results[myFields[i].name]=0;
//What is being iterated here and why?
if(myFields[i].checked) results[myFields[i].name]++;
}
}

//I never seen a for loop statment saying for(fieldName in results)...Is this new syntax and what is it equivalent to??	
for(fieldName in results)if(results[fieldName]==0) resultString+= " "+fieldName;

if(resultString!="") alert("Fields are required, but missing:\n"+resultString);
}
 
try this long hand version :

function val(){
var myForm=document.getElementById("myForm");
var myFields=myForm.getElementsByTagName("input");
var results={};
var resultString="";

for (var i=0;i<myFields.length;i++)
{
if(myFields.type=="radio")
{
if(results[myFields.name]==undefined)
{
results[myFields.name]=0;
}

if(myFields.checked)
{
results[myFields.name]++;
}
}
}

for(fieldName in results)
{
if(results[fieldName]==0)
{
resultString+= " "+fieldName;
}
if(resultString!="")
{
alert("Fields are required, but missing:\n"+resultString);
}
}

Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top