Entry
How can I validate ONLY one radio button in a form?
Jun 24th, 2004 20:45
Michael Phipps, Carlos Prieto,
Javascript is looking for an array when handling radio buttons. When
you have one radio button, there isn't an array. To get arround this,
add a hidden field with the same name as your radio button BEFORE the
radio button.
eg:
<form method="post" action="" onsubmit="return validate(this);">
<input type="hidden" name="foo" />
<input type="radio" name="foo" value="bar" />
<input type="submit" name="btnSubmit" />
</form>
Now the usual validation scripts will work. for example:
<script>
<!--
function validate(frm){
var radioselected=false;
for(t=0;t<frm.foo.length;t++){
if (frm.foo[t].checked) radioselected=true;
}
if (radioselected){
alert("A radio button has been selected");
}else{
alert("A radio button is not selected");
}
}
-->
</script>