SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast magnam's Avatar
    Join Date
    Jun 2006
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Check multiple checkboxes before enabling submit button?

    I can only find code that works with one checkbox.

    How can I make it so the user has to check multiple checkboxes before the submit button is enabled?

  2. #2
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Put references to the checkboxes in an array. Then create a function to iterate through the array - as soon as a checkbox is not checked, return false. If all are okay return true.
    If the function returns true, enable the submit button.

    Or something like this:
    Code:
    <form name="checkboxForm" id="checkboxForm" action="" method="post">
    <input type="checkbox" value="1" />First<br />
    <input type="checkbox" value="2" />Second<br />
    <input type="checkbox" value="3" />Third<br />
    <input type="submit" value="Submit" disabled="disabled" id="submitBtn" />
    </form>
    
    
    <script type="text/javascript">
    var chks = [];
    getBoxes();
    
    function getBoxes() {
      var form = document.getElementById("checkboxForm");
      var inputs = form.getElementsByTagName("input");
      
      for (var i = 0, len = inputs.length; i < len; i++) {
        if (inputs[i].type == "checkbox") chks.push(inputs[i]);
    	inputs[i].onclick = checkBoxes;
      }
    }
    
    function checkBoxes() {
      for (var i = 0, len = chks.length; i < len; i++) {
        if (!chks[i].checked) {
      	  document.getElementById("submitBtn").disabled = true;	  
    	  return;
    	}
      }
      
      document.getElementById("submitBtn").disabled = false;
    }
    </script>


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
  •