faqts : Computers : Programming : Languages : JavaScript : Forms : Radio buttons

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 28 people (68%) answered Yes
Recently 9 of 10 people (90%) answered Yes

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>