Wednesday, October 04, 2006

Checkbox as Radio Buttons

Sometimes you want the appearance of a checkbox on your form, but you want it to function like a radio button where only a single option can be selected at a time. The following JavaScript function will make a group of checkboxes function like a radiogroup.

function singleSelectCheckbox(checkbox) {
var aGroup = checkbox.parentNode;
var allInputs = aGroup.getElementsByTagName("input");
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i] == checkbox) {
continue;
} else {
allInputs[i].checked = false;
}
}
}

This assumes you've placed the checkboxes to work as a radio button group in some sort of containing HTML element (a td or span or something like that).
Your HTML code would look something like:

<span>
<input onclick="singleSelectCheckbox(this)" type="checkbox">Option 1</input>
<input onclick="singleSelectCheckbox(this)" type="checkbox">Option 2</input>
<input onclick="singleSelectCheckbox(this)" type="checkbox">Option 3</input>
</span>

No comments: