Looping through a set of checkboxes to authenticate

Discussion in 'JavaScript' started by Sean@WMS, Oct 30, 2008.

  1. #1
    I have a form I'm working on with a series of checkboxes, reg0 through reg11, that I'm trying to validate to make sure at least one was checked. However, there are other checkboxes on the form, so I can't just simply count up all of the checkboxes -- I need to check against this specific set of them.

    Here's what I've tried:
    
     // Check to make sure at least one workshop was selected
     var checkbox_choices = 0;
     for (counter = 0; counter < 11; counter++)
     {
      if (form.reg[counter].checked)
      { checkbox_choices = checkbox_choices + 1; }
     }
     
     if (checkbox_choices < 1 )
     {
     alert("Please select at least one workshop." + checkbox_choices);
     form.reg0.focus();
     return (false);
     }
    
    Code (markup):
    I also tried if (form.reg+counter.checked), and that had the curious effect of not erroring, but not counting checkbox_choices either, so it always throws the alert and returns false.
     
    Sean@WMS, Oct 30, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    
    <form action="" method="">
       <fieldset id="set_of_checkboxes">
          <input type="checkbox" ...  />
         <input type="checkbox" ...  />
         <input type="checkbox" ...  />
       </fieldset>
    
    </form>
    
    HTML:
    
    var set_of_checkboxes=document.getElementById('set_of_checkboxes');
    var array_of_all_checkboxes=set_of_checkboxes.getElementsByTagName('input');
    //or you may also use
    var array_of_all_checkboxes=set_of_checkboxes.childNodes;
    //now iterate the array using for...in loop
    
    Code (JAVASCRIPT):
     
    rohan_shenoy, Oct 31, 2008 IP
    Sean@WMS likes this.
  3. ranabra

    ranabra Peon

    Messages:
    125
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Here's another option:

    <SCRIPT LANGUAGE="JavaScript">
    var checkbox_selected="";

    function CheckIfcheckboxButtons()
    {
    if (checkbox_selected=="")
    alert("\nYou must check one of the checkbox buttons.");
    else
    {
    alert("Form has been filled out correctly.");
    }
    }
    </SCRIPT>

    <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">YES
    <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">NO
    <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">MAYBE

    <INPUT TYPE="button" VALUE="Check Form Fields" onClick="CheckIfcheckboxButtons()">
     
    ranabra, Oct 31, 2008 IP
  4. Sean@WMS

    Sean@WMS Peon

    Messages:
    134
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks, Rohan. Worked like a charm :)

     
    Sean@WMS, Oct 31, 2008 IP