Click to See Complete Forum and Search --> : Why is the field.length value of a checkbox undefined?


acoble
12-15-2002, 07:57 PM
Why does the script show a value of undefined when there is only one checkbox? It will show a length of 2 for two fields.


<HTML>
<SCRIPT LANGUAGE="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}

function checkForNoSelection(field)
{
var checked = false;
alert("Field length is: " + field.length);
for (i = 0; i < field.length; i++) {
if (field[i].checked == true) {
checked = true;
}
}
if (checked == false) {
alert("Please make a selection.");
return false;
}
}

</script>

<HEAD>
</HEAD>

<BODY>
<form name="FileList" method="post" OnSubmit="return checkForNoSelection(document.FileList.filestr);">
Select "Do It" and a pop-up shows the checkbox length is undefined.<br>
<input name="filestr" type="checkbox" value="R50602D.TRZ">r50602d.trz
<br>
<input name=submit type = "submit" value = " Do It ">
<br>
<input type="button" name="CheckAll" value="Check All" onClick="checkAll(document.FileList.filestr)">
<br>
<input type="button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.FileList.filestr)">
<br>
<br>
</form>
<form name="FileList2" method="post" OnSubmit="return checkForNoSelection(document.FileList2.filestr);">
Select "Do It" and a pop-up shows the checkbox length is 2.<br>
<input name="filestr" type="checkbox" value="R50602D.TRZ">r50602d.trz
<br>
<input name="filestr" type="checkbox" value="R50505D.TRZ">r50505d.trz
<br>
<input name=submit2 type = "submit" value = " Do It ">
<br>
<input type="button" name="CheckAll" value="Check All" onClick="checkAll(document.FileList2.filestr)">
<br>
<input type="button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.FileList2.filestr)">
</form>
</BODY>
</HTML>

khalidali63
12-16-2002, 12:11 AM
you actually should be doing one of these 2.
Either pass the form object that has an array of elements and then form.length will give you total number of elements of which you can loop through..or better yet stick with value you pass to function( a checkbox object) and instead of trying to loop through just do a test for
if (field.checked){
//field is selected .process
}else{
//field is un checked. process
}

Khalid

acoble
12-16-2002, 06:14 AM
Thank you for your help.
Since the HTML page that has the checkboxes is generated based on data and created using ASP, I don't know how many checkboxes there will be. With you input, I used an IF statement to determine if the field was defined.

function checkAll(field)
{
if (field.length){
for (i = 0; i < field.length; i++)
field[i].checked = true ;
} else {
if (! field.checked){
field.checked = true;
}
}
}