Hey Gregory,
this code will work in Netscape 4, Netscape 6 and IE 4+:
<html>
<head>
<title>Checkboxes</title>
<script language="JavaScript" type="text/javascript">
<!--
function loopCheckboxes(){
var oForm = document.forms["theForm"];
var bIsChecked = false;
for(var i=0; i<oForm.elements.length; i++){
if(eval("typeof oForm.ftype_" + i + "!
'undefined'")){
if(eval("oForm.ftype_" + i + ".checked"))
bIsChecked = true;
}
}
if(!bIsChecked){
alert("You need to check one of the boxes!");
}
}
//-->
</script>
</head>
<body>
<form name="theForm">
<input type="checkbox" name="ftype_0">
<input type="checkbox" name="ftype_1">
<input type="radio" name="radioButton">
<input type="checkbox" name="ftype_2">
<input type="text" name="textField">
<input type="checkbox" name="ftype_3">
<input type="button" name="aButton" value="loopTrough"
onClick="loopCheckboxes()">
</form>
</body>
</html>
/Robert
-----Original Message-----
From: Gregory Reddin [mailto:greddin@y...]
Sent: den 20 november 2001 17:27
To: JavaScript HowTo
Subject: [javascript_howto] RE: Looping through checkboxes
I would really like to target IE 4+ and Netscape 4+ and up.
> Oh, of course!
>
> This line messes it up:
>
> var oCheckbox = eval("document.forms(0).ftype_"+i);
>
> for obvious reasons...
>
> Which browsers are you targetting?
>
>
> /Robert
>
>
>
> -----Original Message-----
> From: Gregory Reddin [mailto:greddin@y...]
> Sent: den 20 november 2001 17:12
> To: JavaScript HowTo
> Subject: [javascript_howto] RE: Looping through checkboxes
>
>
> Ok, I tried this and get the following browser (IE 5.5) error:
>
> Error: 'undefined' is not an object
>
> Thank you,
> -Greg
>
>
>
> > Try:
> >
> > for(i=1;i<=document.forms(0).length;i++)
> >
> > AND
> >
> > if(typeof oCheckbox.checked != "undefined"){
> > if(oCheckbox.checked) bFlag = true;
> > }
> >
> >
> > /Robert
> >
> >
> > -----Original Message-----
> > From: Gregory Reddin [mailto:greddin@y...]
> > Sent: den 20 november 2001 16:58
> > To: JavaScript HowTo
> > Subject: [javascript_howto] RE: Looping through checkboxes
> >
> >
> > Thank you both for such excellent solutions. In the solution below,
> would
> > there be a better way to make the "4" in the "for loop" dynamic?
> > I tried for(i=1;i<=document.forms(0).length;i++) but that craps out
> > because most of the elements on my form at not checkboxes. How could I
> get
> > around that?
> >
> >
> > var bFlag = false;
> > for(i=1;i<=4;i++){
> > var oCheckbox = eval("document.forms(0).ftype_"+i);
> > if(oCheckbox.checked) bFlag = true;
> > }
> > if(!bFlag){
> > alert("Please check a checkbox");
> > }
> >
> >
> robert.nyman@i...
> > $subst('Email.Unsub')
>
robert.nyman@i...
> $subst('Email.Unsub')
$subst('Email.Unsub')