Show group based on the number of selected checkboxes

Say you have 5 checkboxes and you want some fields to appear when at least 3 are checked? With the free version of Conditional Fields this isn’t possible. But with Conditional Fields Pro you can add a function name as a condition, and depending on whether or not this function returns true, the fields will respectively be shown or hidden.

Form

    Select at least 3 letters:

    Cool! You have selected at least three checkboxes.

    What's your name?


    Form Code

    Select at least 3 letters:
    [checkbox letters use_label_element "A" "B" "C" "D" "E"]
    [group threeselected]
      <strong>Cool! You have selected at least three checkboxes.</strong>
      
      What's your name?
      [text your-name]
    [/group]
    [submit]
    <script>
      function hasThreeOrMoreSelected(field) {
        // note that right now we are still passing the jQuery field. But because WP and CF7 are moving away from jQuery, field will eventually be replaced by the actual DOM element. The check below ensure backwards compatibility when that time comes.
        if (field instanceof jQuery) {
          field = field[0];
        }
        const numChecked = document.querySelectorAll(`[name="${field.getAttribute('name')}"]:checked`).length;
        return numChecked >= 3;
      }
    </script>

    Conditional Fields (Text)

    show [threeselected] if [letters] function "hasThreeOrMoreSelected"

    (Related GitHub issue: https://github.com/pwkip/contact-form-7-conditional-fields/issues/24)

    First, let’s write the JavaScript function.

    function hasThreeOrMoreSelected(field) {
      if (field instanceof jQuery) {
        field = field[0];
      }
      const numChecked = document.querySelectorAll(`[name="${field.getAttribute('name')}"]:checked`).length;
      return numChecked >= 3;
    }

    You can add this function to your theme’s JS file, or to your form directly. If you choose to do the latter, make sure to not add any blank lines, as CF7 might convert these to paragraphs automatically.

    Add the condition

    Now that we have the function in place, we can add this condition:

    show [letters] if function hasThreeOrMoreSelected