Click to See Complete Forum and Search --> : How to count checkboxes on page


damon2003
11-13-2003, 08:18 AM
HI,
I have a script that produces varying number of checkboxes depending on what the user does. They are called checkbox1 , checkbox2, checkbox3 and so on

I want to make sure that at least one of these is checked. So as I do not know the total no, I am thinking that I will have to first of all count the number of checkboxes on the page. How can I count the number of checkboxes on the page,
thanks a lot

fredmv
11-13-2003, 08:40 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>untitled</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=iso-8859-1" />
<script type="text/javascript">
//<![CDATA[
function go()
{
var
inputs = document.getElementsByTagName('input'),
checkboxes = 0,
one = false,
i = 0,
j = 0;

do
{
if(inputs[i].type.toLowerCase() == 'checkbox')
{
checkboxes++;
}

i++;
}
while(i < inputs.length);

do
{
if(inputs[j].type.toLowerCase() == 'checkbox' && inputs[j].checked == true)
{
one = true;
break;
}

j++;
}
while(j < inputs.length);

alert("number of checkboxes: \t" + checkboxes + "\natleast one is checked: \t" + one);

}
//]]>
</script>
</head>
<body>
<form action="#">
<div>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<hr />
<input type="button" onclick="go();" value="Get Current Status" />
</div>
</form>
</body>
</html>