Require At Least One Checkbox

An example of having more than one checkbox where the form cannot be submitted unless at least one checkbox is checked.

by Travis Almand

HTML

<p>One of these checkboxes must be checked or the submit button can not be clicked.</p>

<p>Clean CSS version:</p>
<form id='form1' onsubmit='alert("submit1"); return false;'>
  <input type='checkbox' name='test1' value='red' />
  <input type='checkbox' name='test1' value='blue' />
  <input type='checkbox' name='test1' value='green' />
  
  <input type='submit' value='send' />
</form>

<p>Pre-IE11 supported version:</p>
<form id='form2' onsubmit='alert("submit2"); return false;'>
  <input type='checkbox' name='test2' value='red' />
  <input type='checkbox' name='test2' value='blue' />
  <input type='checkbox' name='test2' value='green' />
  <span class='submit-container'>
    <input type='submit' value='send' />
  </span>
</form>

<p>CSS targets submit button with opacity and disables pointer events. A checked checkbox then cascades down to submit to restore its opacity and pointer events.</p>
<p>Keep in mind that the CSS must be able to select the submit button from the checkboxes, so no parents for checkboxes that the submit does not share.</p>
<p>Since this requires CSS pointer-events support the usual IE will be an issue. The second version shows an alternate way to do it for pre-IE11 versions. It essentially wraps the submit in a span to make a :before pseudo element to cover the submit, preventing a click, until a checkbox is checked. </p>

SCSS

form {
  border: 1px solid gainsboro;
  margin: 10px;
  padding: 10px;
}
#form1 {
  input[type='submit'] {
    opacity: 0.5;
    pointer-events: none;
  }
  input[type='checkbox']:checked ~ input[type='submit'] {
    opacity: 1;
    pointer-events: auto;
  }
}

#form2 {
  .submit-container {
    position: relative;
    
    &:before {
      background-color: rgba(255, 255, 255, 0.01);
      bottom: -3px;
      content: '';
      display: block;
      left: 0;
      position: absolute;
      right: 0;
      top: -3px;
      z-index: 10;
    }
  }
  input[type='submit'] {
    opacity: 0.5;
  }
  input[type='checkbox']:checked ~ .submit-container {
    &:before {
      display: none;
    }
    input[type='submit'] {
      opacity: 1;
    }
  }
}