Click to See Complete Forum and Search --> : Validate Radio Button


critters
05-08-2003, 08:09 PM
I'm stumped! I need to do a very simple validation - did one of the radio buttons get checked (there are two)?

This is what I'm trying to do:
}
//Validate the CD Field
if(document.Order1.CD[0].checked &&
document.Order1.CD[1].checked )
{
alert("Please choose if you wish a CD");
document.Order1.CD.focus();//Focus on the field
return false;
}

What am I doing wrong??

Thanks for any help!

Critters

pyro
05-08-2003, 08:42 PM
You are using && (and). Obviously both of the radio buttons can't be checked at the same time. Try using || (or) like this:

if (document.Order1.CD[0].checked || document.Order1.CD[1].checked )

pyro
05-08-2003, 09:34 PM
Umm... your code will behave no differntly from mine, besides the fact that it is checking to make sure that the radio buttons aren't checked. Due to the way that radio buttons work, only one can be checked, so my code is checking if either of them are. Yours is checking if they both aren't. Same results...You find out whether or not a button had been selected....

pyro
05-08-2003, 09:42 PM
But, if you negate my code (or put the alert, etc code in an else), it should simply check to make sure that neither one are checked...

pyro
05-08-2003, 09:49 PM
Next time I will be more clear. This is the code that I was implying...

if(document.Order1.CD[0].checked || document.Order1.CD[1].checked ) {
}
else {
alert("Please choose if you wish a CD");
document.Order1.CD.focus();
return false;
}

And don't come back on and say "you could just negate it to get rid of the else loop." I already said that...

critters
05-08-2003, 09:52 PM
I tried the || but it didn't work, but when I used the exclamation marks with the && it worked. But I had to remove the focus because it gave me an error, but when I did, it works great now.

Thanks, guys!!

Critters

pyro
05-08-2003, 09:59 PM
Sorry, don't mean to be touchy. Just couldn't see why you coudn't see how the way that I posted could work. I agree, yours is more intuitive, but stand by the fact that mine will work for what he was trying to do... Peace?

pyro
05-08-2003, 10:13 PM
<html>
<head>
<script language="javascript" type="text/javascript">
function test() {
if(document.Order1.CD[0].checked || document.Order1.CD[1].checked ) {
}
else {
alert("Please choose if you wish a CD");
document.Order1.CD[0].focus();
return false;
}
}
</script>
</head>
<body>
<form name="Order1">
<input type="radio" name="CD" value="zero">
<input type="radio" name="CD" value="one">
<input type="button" value="test" onclick="test();">
</form>
</body>
</html>