Click to See Complete Forum and Search --> : Radio button validation


rowantrimmer123
06-11-2009, 03:01 PM
Hello,

I have 2 radio buttons and I need to write a script that checks that 1 of the 2 radio buttons has been checked as they cannot both be unchecked.

My html for the form is as follows...

<tr>
<td colspan="2" class="formname"><b><span style="COLOR: red">*</span>Are you a Parent?</b>&nbsp;&nbsp;&nbsp;<input name="person" type="radio" value="1" /></td>
</tr>
<tr>
<td colspan="2" class="formname"><b><span style="COLOR: red">*</span>Are you a Teacher?</b>&nbsp;<input name="person" type="radio" value="2" /></td>
</tr>

I would really appreciate the code for the javascript.

Kind Regards


Rowan

djjjozsi
06-11-2009, 03:12 PM
if you create a valid radio botton the visitor could only select one from teh above.

1<input type="radio" id="test" name="test" value="1"><br />
2<input type="radio" id="test" name="test" value="2"><br />

Weedpacket
06-11-2009, 10:29 PM
1<input type="radio" id="test" name="test" value="1"><br />
2<input type="radio" id="test" name="test" value="2"><br />
Uh, that's not valid; you've got two elements with the same id :)
The issue that needs addressing is that there's nothing there to require selecting one of the options.

I would really appreciate the code for the javascript.So why post in a PHP forum? Moving the thread.

djjjozsi
06-12-2009, 08:12 AM
Thanks Weedpacket that you warned me about my mistake.

bradgrafelman
06-12-2009, 03:15 PM
Here's the way I normally do it:

<script type="text/javascript">
function validateRadio(frm) {

for (i = 0; i < frm.test.length; i++)
if(frm.test[i].checked)
return true;

alert('Error: You must select an option!');
return false;

}
</script>
<form onsubmit="return validateRadio(this)">
1<input type="radio" name="test" value="1"><br />
2<input type="radio" name="test" value="2"><br />
<input type="submit">
</form>

or you could make the function more generalized to suit multiple radio groups:

<script type="text/javascript">
function validateRadio(frm, name) {

for (i = 0; i < frm[name].length; i++)
if(frm[name][i].checked)
return true;

alert('Error: You must select an option!');
return false;

}
</script>
<form onsubmit="return validateRadio(this, 'test')">
1<input type="radio" name="test" value="1"><br />
2<input type="radio" name="test" value="2"><br />
<input type="submit">
</form>