Count checked checkboxes with getElementById

P

pieter.thoma

Hi,

I'm trying to count the number of selected checkboxes with the
following code, but I don't get any result, unless I explicitly
hardcode the form.chckbox-name.

This doesn't work:

function anyCheck(this) {
var total = 0;
var max = document.getElementById("cbox").length;
for (var idx = 0; idx < max; idx++) {
if (eval("document.getElementById[" + idx + "].checked") == true) {
total += 1;
}
}
alert("You selected " + total + " boxes.");
}

This does:

function anyCheck(form) {
var total = 0;
var max = form.ckbox.length;
for (var idx = 0; idx < max; idx++) {
if (eval("form.ckbox[" + idx + "].checked") == true) {
total += 1;
}
}
alert("You selected " + total + " boxes.");
}
 
D

David Dorward

I'm trying to count the number of selected checkboxes with the
following code, but I don't get any result, unless I explicitly
hardcode the form.chckbox-name.

This doesn't work:
var max = document.getElementById("cbox").length;

Do you have multiple elements with the same id? That isn't allowed.
Validate. Validate. Validate.
for (var idx = 0; idx < max; idx++) {
if (eval("document.getElementById[" + idx + "].checked") == true) {

* eval should almost never be used
* document.getElementById is a function, don't try to treat it like an
object. Don't use [].
* An id can't start with a number. Validate. Validate. Validate.
function anyCheck(form) {
var total = 0;
var max = form.ckbox.length;
for (var idx = 0; idx < max; idx++) {
if (eval("form.ckbox[" + idx + "].checked") == true) {

http://www.dev-archive.net/articles/js-dot-notation/ might be useful
in avoiding eval.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top