Forum Moderators: open
x=document.myForm;
if (!(x.Item7.checked))
{ message += "Select Item 7";
submitOK="False"; }
example:
accessBool = -1;
for (counter=0; counter<3; counter++) {
if (form.radio_group_name[counter].checked == true {
accessBool = counter;
}
}
then if 'counter' is -1 at the end, you know nothing was checked.
In the array itself, you start with 0 and increment the count with each item. A three-item array will index its entries as Item7[0], Item7[1], Item7[2].
Javascript takes the length as the number of items in the array. In other words: a three-item array will have a length of 3, according to Javascript.
for(counter=0;counter<=Item7.length-1;counter++)
is more "satisfying" to Javascript. While your script
for(counter=0;counter<Item7.length;counter++)
would seem to be identical, it is not the recommended way of using comparison operators in Javascript.
The reason is that there is an extra/aborted loop that begins during the final iteration, where Javascript "sees" that it's final increment (++) is over the limit, and cancels the loop. Using (<=) lets Javascript "know" that THIS is the final iteration (=), and to NOT return for a final comparison.
Loop1 = Item7[0] (counter = 0)
Loop2 = Item7[1] (counter = 1)
Loop3 = Item7[2] (counter = 2 = 3-1 = Item7.length-1)
I do realize that this seems a ridiculously small difference, and maybe not even a difference at all! ("What is the difference between 2<3 and 2<=3-1?"), and while I can't explain exactly what the difference is, I do know that the latter (<=) is recommended for best Javascript performance.
:)
How would I turn this into a function that could be used for different sets of radio buttons in a form? I'm not sure how you pass the variable name to the function and then use it in the loop. I mean something like this:
for(counter=0;counter<=(passed name).length-1;counter++)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function chkRads(frm,r1,r2){ //allows two radio button arrays, add parameter names if needed
var rad_arr=[r1,r2];
var rd_ar_ln=rad_arr.length;
var i=0;
while(i<rd_ar_ln){
var curr_rad=frm[rad_arr[i]];
var rad_len=curr_rad.length;
for(var n=0;n<rad_len;n++){
if(curr_rad[n].checked)break;
else if(n==rad_len-1){
alert("you blew it");
return false;
}
}
i++;
}
return true;
}
</script>
</head>
<body>
<form action="javascript:alert('you made it');" onsubmit="return chkRads(this,'rad1','rad2');">
<p>
<input type="radio" name="rad1" value="a" />a
<input type="radio" name="rad1" value="b" />b
<input type="radio" name="rad1" value="c" />c
</p>
<p>
<input type="radio" name="rad2" value="1" />1
<input type="radio" name="rad2" value="2" />2
<input type="radio" name="rad2" value="3" />3
</p>
<input type="submit" />
</form>
</body>
</html>