Results 1 to 2 of 2

Thread: Validate many checkbox-same name ?

  1. #1
    Join Date
    Jul 2008
    Posts
    18
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Post Validate many checkbox-same name ?

    Hi.
    I have a code with 5 check boxes with same name and different Id's.
    I need to validate the check boxes that before submitting at least one of the check box must be checked.
    Can u give me a sample code and suggest me a logic, that how i can achieve it.

    Thanks in advance.
    regards,
    satheeshkannan.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    With five checkboxes, all with the same name, as long as you don't have other checkboxes or radio buttons in the form with that name, this will work:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function oneOfFive(f){
    for (var e = f.elements, i = e.length - 1; i > -1; --i)
    if(e[i].name && e[i].name == 'bob' && e[i].checked)
    return true;
    alert('Please Check at Least One box');
    return false;
    }
    </script>
    </head>
    <body>
    <form action="#" onsubmit="return oneOfFive(this);">
    <input type="checkbox" name="bob" value="">
    <input type="checkbox" name="bob" value="">
    <input type="checkbox" name="bob" value="">
    <input type="checkbox" name="bob" value="">
    <input type="checkbox" name="bob" value="">
    <input type="submit" value="Go!">
    </form>
    </body>
    </html>
    Pretty much whatever else you want to have is up to you. You can give them each an id (all id's must be unique according to spec, and at least for most purposes involving javascript). You can have other elements in the form. Each box can have a value, label, etc.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •