Showing posts with label radiobuttonlist. Show all posts
Showing posts with label radiobuttonlist. Show all posts

Tuesday, November 30, 2010

validating dynamically created radiobuttonlists

I recently was working on writing a client validation function to go hand in hand with my customvalidator. My form had some regular ASP controls on it, and it also had a section of questions inside a repeater, since this section was designed to ask you to rate instructors, and the name and quantity of said instructors depended on which class it was. I don't remember trying to write javascript to check radiobuttonlists inside a repeater before but eventually read a helpful snippet here.

In the example at that link, the entire form is iterated through. In my case however the form had radipbuttonlists both in and out of the repeated, and I only wanted to iterate through the repeater for this check. I already had simpler functions for the rest of them. Additionally I did not want a message to pop up for every unanswered radiobuttonlist in this section, but merely one generic "please rate all instructors" message. So I wrapped the repeater in a div, and it is this div that the variable called container below references.


// Grabs all inputs - radio, checkbox, text, buttons and lists -sticks them in an array
var last = "NameUnlikelyToBeUsedAsAnElementName";

var container = document.getElementById("divRpt");
var allInputs = container.getElementsByTagName("input");

// walk through the array
for (i = 0; i< allInputs.length; i++)
{
var input = allInputs[i];
if (input.name == last) continue; // if this object name is the same as the last checked radio, go to next iteration

// checks to see if any one of similarly named radiobuttons is checked
else if (input.type == "radio" )
{
last = input.name;
var radios = document.getElementsByName(input.name);
var radioSelected=false;

//iterate over question options
for (j=0; j < radios.length; j++)
{
if(radios[j].checked)
{
radioSelected=true;
break; // Found it, proceed to next question
}
}
if (!radioSelected) // no option selected
{
bOK = false;
}
}
if (!bOK){alert("Please rate the overall teaching effectiveness for your instructor(s)");}