Validate that at least one checkbox is checked

Discussion in 'Javascript' started by Zvonko Bi¹kup, Mar 13, 2007.

  1. Hi!

    I have 5 checkboxes with the same name:
    <input type="checkbox" name="check" value="XYZ" />
    <input type="checkbox" name="check" value="ZXY" />
    <input type="checkbox" name="check" value="MHG" />
    <input type="checkbox" name="check" value="IOJ" />
    <input type="checkbox" name="check" value="BGT" />

    How to check if at least one is checked?

    Thanks
    Zvonko
     
    Zvonko Bi¹kup, Mar 13, 2007
    #1
    1. Advertising

  2. Zvonko Bi¹kup

    Ivo Guest

    "Zvonko Bi¹kup" wrote
    > I have 5 checkboxes with the same name:
    > <input type="checkbox" name="check" value="XYZ" />
    > <input type="checkbox" name="check" value="ZXY" />
    > <input type="checkbox" name="check" value="MHG" />
    > <input type="checkbox" name="check" value="IOJ" />
    > <input type="checkbox" name="check" value="BGT" />
    >
    > How to check if at least one is checked?


    Assuming they are inside a form named "f", try something like:

    var els = document.forms.f.elements;
    var i = els.length;
    var flag = false;
    while( i-- ) {
    if( els.name==='check' && els.checked ) {
    flag = true; break;
    }
    }
    alert( flag ? 'There is a checkbox checked' : 'Try again.' );

    hth
    ivo
    http://4umi.com/web/javascript/
     
    Ivo, Mar 13, 2007
    #2
    1. Advertising

  3. Zvonko Bi¹kup

    -Lost Guest

    "Zvonko Bi¹kup" <> wrote in message
    news:45f64915$-net.net...
    > Hi!
    >
    > I have 5 checkboxes with the same name:
    > <input type="checkbox" name="check" value="XYZ" />
    > <input type="checkbox" name="check" value="ZXY" />
    > <input type="checkbox" name="check" value="MHG" />
    > <input type="checkbox" name="check" value="IOJ" />
    > <input type="checkbox" name="check" value="BGT" />
    >
    > How to check if at least one is checked?


    document.forms['form_name'].elements['check'] will give you a nodeList of your checkboxes.
    You can then iterate them with a loop checking for the "checked" value to be true. If
    none are true, nothing is checked.

    -Lost
     
    -Lost, Mar 13, 2007
    #3
    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. yurps
    Replies:
    1
    Views:
    6,927
    rajeshthangarasu1983
    Feb 29, 2008
  2. Homer
    Replies:
    1
    Views:
    460
    Sherif Elmetainy
    Aug 29, 2007
  3. AAaron123
    Replies:
    0
    Views:
    614
    AAaron123
    Oct 3, 2008
  4. NotGiven
    Replies:
    5
    Views:
    183
    Thomas 'PointedEars' Lahn
    Feb 12, 2004
  5. DoomedLung
    Replies:
    2
    Views:
    119
    DoomedLung
    Sep 28, 2006
Loading...

Share This Page