More cut & paste JavaScript Goodies
Validating large radio button arrays
I have seen some absolutely silly code to loop through large groups of radio buttons on forms so I thought I would throw this code up to simplify this for some of you. Its really quite simple actually, you just loop through the array of buttons looking for one that is checked. If it is found the variable check is set to true and the form is submitted. If no checked button is found the variable stays false and the alert is thrown. This code also requires using a break statement to a label to stop the loop if it finds a checked button. Here's how it works:
<SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
function radioCheck(form) {
var check;
outerloop:
for (x = 0; x < form.conType.length ; x++ ) {
if (form.conType[x].checked) {
check = true;
break outerloop;
}
else {
check = false;
}
}
if (!check) {
alert("Please select the reason for this contact");
return false;
}
}
//-->
</SCRIPT>
In this code your radio buttons are called conType and, as always the form tag must call this function and pass (this) to the function. This is how your form tag should look:
<FORM METHOD=POST ACTION="yourAction" onSubmit="return radioCheck(this);">
This just seems a lot more logical to me than writing an if statement a mile long that checks all the buttons in the if!
Theresa Judd, permanentcosmeticsbytheresa.com | More Testimonials >>