Forum Moderators: open

Message Too Old, No Replies

Is there any other ways to do this?

code to validate 50+ groups of radio buttons

         

someone

6:03 pm on Dec 22, 2004 (gmt 0)

10+ Year Member



I have 50+ groups of radio buttons with each group containing 5 choices. I have this code here that checks to ensure that the user has checked all 50+ groups.

function form_checker() {
//-------radio group #1
var radio_choice1 = false;
for (counter = 0; counter < myForm.Q1.length; counter++)
{
if (myForm.Q1[counter].checked)
radio_choice1 = true;
}
if (!radio_choice1)
{
alert("Please mark #1.")
return (false);
}
//----------radio group #2
var radio_choice2 = false;
for (counter = 0; counter < myForm.Q2.length; counter++)
{
if (myForm.Q2[counter].checked)
radio_choice2 = true;
}
if (!radio_choice2)
{
alert("Please mark #2.")
return (false);
}

//----------radio group #3
var radio_choice3 = false;
for (counter = 0; counter < myForm.Q3.length; counter++)
{
if (myForm.Q3[counter].checked)
radio_choice3 = true;
}
if (!radio_choice3)
{
alert("Please mark #3.")
return (false);
}
}

........i do the same thing for the rest of the groups. So obviously the code does not look so clean and is very long although it works perfectly fine. I was wondering what other ways can I shorten the code a bit besides using a switch statement? Would a for loop or some other loops work in this case? If so, could someone give me some hints? Thanks.

orion_rus

6:28 pm on Dec 22, 2004 (gmt 0)

10+ Year Member



He he he))) good decision) but i suggest you two ways u can choose any of it:
1.

function CheckAllbuttons()
{radstr="radiobutton";
for (var i=0;i<51;i++)
{checkbuttons=false;
tempstr=radstr+i;
radioelement=document.getElementById(tempstr);
{for (counter=0;counter<radioelement.length;counter++)
{if (radioelement[counter].checked) {checkbuttons=true;}
}
if (checkbuttons==false) {alert("Fill "+i+" radioelement");
}
}
}
2. Second way much simple. If anybody checked a radiobutton, this input have onchange event. U can make onchage=function MakeTrue("radiobutton5")
function MakeTrue(elem)
{checkbuttons[elem]=true;}
and after submit you should check checkbuttons array, for validating for true all array

Good luck to you