Radio buttons are the one field type in a form where you need to use getElementByName instead of getElementById at least some of the time. The reason for this is that radio buttons form a group based on the name of the field whereas the id must be unique. While you might set a particular radio button using its id, the only way to properly validate radio buttons is to validate the entire group.
In this example we have a simple function that will validate whether the radio button group is valid by testing whether any of the buttons have been checked.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D03</title>
</head>
<body>
<form action="#">
<div>
<input type="radio" id="r1" name="size" value="s" />
<label for="r1">Small</label>
<input type="radio" id="r2" name="size" value="m" />
<label for="r2">Medium</label>
<input type="radio" id="r3" name="size" value="l" />
<label for="r3">Large</label>
</div>
</form>
<script type="text/javascript" src="exampleD03.js"></script>
</body>
</html>
JavaScript
valButton = function(btn) {
for (var i=btn.length-1; i > -1; i--) {
if (btn[i].checked) return btn[i].value;
}
return null;
}
valForm = function() {
if (null === valButton(document.getElementsByName('size'))) {
// code for when radio button not selected
}
// rest of field validations
}
