Showing posts with label checkboxlist. Show all posts
Showing posts with label checkboxlist. Show all posts

Friday, August 22, 2008

toggleOptions

Hi guys!

Miss me? How can you miss me if I keep blogging! :P

OK so as you know I added a code library to the repo. I put all the Javascript we had already collected into it. The trouble is it's disorganized and some of it is pretty old and possible inefficient or not the best code. Therefore I hope to clean up the library to only have clean and good code :) And in an effort to do this AND organzie, from now on when I can I will add scripts into subfolders. I will label the folders by control type. Then inside the folder will be all the different scripts. So, if the JS is in a subfolder of Javascript, then it has been "quality controlled."

Please feel free to aid my efforts! Remember when you add a script to add a comment with your initials so we know who to ask if we have questions about the code!

Myself, I will try to blog whenever I add a script.

OK on to today's script. We may already have had something like this, I don't know. It was a mess in there so I didn't find it.

This function was written for those times when one of the options you pick should make all of the other options invalid. For example let's say the question is What color do you like best: red, green or none of the above? None of the above should obviously make it impossible to check red or green.

The code below is specifically for ASP:CheckBoxList, hence the part where I format the field's name as name = fieldName + "_" + i; because .NET takes the ListItem in a CheckBoxList and names it controlId_indexOfItem. If in my example the control was called cblColor then in the HTML red would have the id cblColor_0, and green would be cblColor_1 etc etc.

The parameters: optionToFocusOn is the one that triggers the function. In my example it would be cblColor_2, the none of the above. totalOptions is the total number of options, and in my example would be 3. fieldName would be the id of the control itself; in my example it would be cblColor.


//toggle options on and off - for use when one selection should disable the rest of the group
//for use with the ASP:CheckBoxList

function toggleOptions (optionToFocusOn, totalOptions, fieldName)
{
var name = fieldName + "_" + optionToFocusOn;
if (document.getElementById(name).checked == true)
{
for (i = 0; i < totalOptions; i++)
{
name = fieldName + "_" + i;
if (i != optionToFocusOn)
{
document.getElementById(name).checked = false;
document.getElementById(name).disabled = true;
}
}
}
else
{
for (i = 0; i < totalOptions; i++)
{
name = fieldName + "_" + i;
if (i != optionToFocusOn)
{
document.getElementById(name).disabled = false;
}
}
}
}