Discovered an anomaly with radio buttons and JavaScript yesterday. Should you create a form that contains just a single radio button rather than a set (as might happen is the form is built dynamically using PHP), a JavaScript array of the radio button will be of undefined length, even though it contains 1 element. You can avoid generating a JavaScript error by first testing to see if the length is 'undefined', thus:
The JavaScript:
function checkForm(form) {
if (typeof form.radioButton.length!="undefined") {
// there must be more than one button
var flag=0;
for (i=0; i< form.radioButton.length; i++) {
if (form.radioButton[i].checked) flag=1;
}
if (flag) return true;
} else {
// there's only one button - so can test directly
if (form.radioButton.checked) {
return true;
}
}
alert ('You must check a radio button');
return false
}
The HTML:
<FORM ACTION='somewhere.php' METHOD='post'>
<INPUT TYPE='radio' NAME='radioButton' VALUE='1'>
<!-- if there were to be more buttons, they would appear here -->
<INPUT TYPE='submit' ONCLICK='return checkForm(this.form);'>
</FORM>
Technorati tags: JavaScript form validation radio buttons