Count checked checkboxes with getElementById

Discussion in 'Javascript' started by pieter.thoma@gmail.com, Dec 17, 2007.

  1. Guest

    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.");
    }
     
    , Dec 17, 2007
    #1
    1. Advertising

  2. On Dec 17, 10:03 am, wrote:
    > 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.

    --
    David Dorward
    http://dorward.me.uk/
    http://blog.dorward.me.uk/
     
    David Dorward, Dec 17, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. DJ Dev
    Replies:
    7
    Views:
    682
    DJ Dev
    Feb 10, 2004
  2. moondaddy
    Replies:
    4
    Views:
    108,625
    TN Bella
    Jun 22, 2004
  3. yurps
    Replies:
    1
    Views:
    6,901
    rajeshthangarasu1983
    Feb 29, 2008
  4. Jim Bancroft
    Replies:
    4
    Views:
    870
  5. gangur
    Replies:
    1
    Views:
    1,571
    ProgTalk
    Feb 22, 2008
Loading...

Share This Page