Saturday, August 11, 2007

Optional Radio Buttons 

It has always bugged me that you can't really make radio buttons optional on web form. You can load all the radio buttons in a group as un-checked, but as soon as the user selects one then a value from that check box group will be submitted.

You can get around this problem by adding one option to the group and labeling it "N/A" or something. This gives the user an out. Incredibly, I have never been able to convince any of my customers to go that route. In fact, even if the radio group is required they will want the all of the options unchecked initially.

Most people get around this by writing their own logic over check boxes, but I decided to take a different approach. I finally wrote some JavaScript which will un-check a radio button if the button you click is already checked, thus allowing the user an escape route.


function RadioClick(radio)
{
var inputs = document.getElementsByTagName("input");
var checked = (radio.getAttribute("shadow") == "true");
for(var i = 0; i < inputs.length; i++)
{
if (inputs[i].getAttribute("type") == "radio" && inputs[i].name == radio.name)
{
inputs[i].setAttribute("shadow", "false");
}
}
if (checked)
{
radio.checked = false;
}
else
{
radio.setAttribute("shadow", "true");
}
}


All you have to do is add this script to your page and then just add "RadioClick" to the radio button's onClick event, like so...


<input id="ctl01" type="radio" name="GroupName" value="ctl01"
checked="checked" onclick="javascript:RadioClick(this);" />


You could easily make this script unobtrusive by adding a method that assigns onClick event by group name when the page loads.

Comments: Post a Comment

This page is powered by Blogger. Isn't yours?