...

View Full Version : validate radio buttons



esthera
03-13-2005, 10:04 AM
I have 2 radio buttons

In my validation javascript I do for example for a select box

if (theForm.category.selectedIndex == 0)
{
alert("The first \"category\" option is not a valid selection. Please choose one of the other options.");
theForm.category.focus();
return (false);
}

How would I do the same to validate that my radio boxes are checked.
For example I have 2 radio buttons called radio1 one with the value yes and one with the value no -- How do I validate that at least one was selected?

vwphillips
03-13-2005, 02:48 PM
There must be an easier way but




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<title></title>

<script language="JavaScript" type="text/javascript">
<!--
var ips,ckd;
var RadAry=new Array();
var GrpAry=new Array();

function CheckRadio(){
ips=document.getElementsByTagName('INPUT');
RadAry=new Array();
for (i=0;i<ips.length;i++){
if (ips[i].type=='radio'){
RadAry[RadAry.length]=ips[i];
}
}
GrpAry=new Array();
GrpAry[0]=new Array();
for (i2=0;i2<RadAry.length;i2++){
GrpAry[GrpAry.length-1][GrpAry[GrpAry.length-1].length]=RadAry[i2];
if (RadAry[i2+1]&&RadAry[i2+1].name!=RadAry[i2].name){
GrpAry[GrpAry.length]=new Array();
}
}
for (i3=0;i3<GrpAry.length;i3++){
ckd=1;
for (i4=0;i4<GrpAry[i3].length;i4++){
if (GrpAry[i3][i4].checked==true){
ckd=0
}
}
if (ckd){
alert('Radio Group '+GrpAry[i3][0].name+' is not checked');
}
}
}

//-->
</script>
</head>

<body>


<input type="radio" name="fred">
<input type="radio" name="fred">
<input type="radio" name="fred">
<br>
<input type="radio" name="tom">
<input type="radio" name="tom">
<input type="radio" name="tom">
<br>
<input type="button" name="" value="Check" onclick="javascript:CheckRadio();">
</body>

<script> vic=0; </script>
<form name=Show id=Show style="position:absolute;visibility:visible;top:450px;left:0px;" >
<input size=10 name=Show1 >
<input size=10 name=Show2 >
<input size=10 name=Show3 >
<input size=10 name=Show4 >
<input size=10 name=Show5 >
<input size=10 name=Show6 >
</form>
</html>

esthera
03-13-2005, 07:15 PM
thanks.

How can I change the checkradio function to return true if a radio button is checked and false if it not?

Brandoe85
03-13-2005, 11:13 PM
Or you could just do a forum search for validate radio button, it's been answered numerous times :p

glenngv
03-14-2005, 07:53 AM
Try this:

function checkRadio(radGrpName){
var radios = document.theForm.elements[radGrpName];
for (var i=0; i<radios.length; i++){
if (radios[i].checked){
return true;
}
}
return false;
}

//sample usage using vwphillips' sample html
if (!checkRadio("fred")){
alert("Radio Group fred is not checked.");
return false;
}
else if (!checkRadio("tom")){
alert("Radio Group tom is not checked.");
return false;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum