#125 - Control Required State With Checkbox v0.1

Set form fields to required/optional based on the state of a checkbox.

View demo

<!-- 💙 MEMBERSCRIPT #125 v0.1 💙 - CHECKBOX TOGGLE REQUIRED ON FORM FIELDS -->
<script>
  // Function to initialize the form field requirements
  function initFormFieldRequirements() {
    // Handle checkbox changes
    document.querySelectorAll('[ms-code-req-if-checked], [ms-code-req-if-unchecked]').forEach(checkbox => {
      checkbox.addEventListener('change', updateFieldRequirements);
      // Initial update
      updateFieldRequirements.call(checkbox);
    });
  }

  // Function to update field requirements based on checkbox state
  function updateFieldRequirements() {
    const isChecked = this.checked;
    const group = this.getAttribute('ms-code-req-if-checked') || this.getAttribute('ms-code-req-if-unchecked');
    const ifChecked = this.hasAttribute('ms-code-req-if-checked');
    const shouldBeRequired = ifChecked ? isChecked : !isChecked;
    const shouldDisableIfNotReq = this.hasAttribute('ms-code-disable-if-not-req');

    // Update associated input fields
    document.querySelectorAll(`[ms-code-req-input="${group}"]`).forEach(input => {
      input.required = shouldBeRequired;
      updateInputStyle(input, shouldBeRequired, shouldDisableIfNotReq);
    });

    // Update associated labels
    document.querySelectorAll(`[ms-code-req-label="${group}"]`).forEach(label => {
      label.style.display = shouldBeRequired ? '' : 'none';
    });
  }

  // Function to update input style based on required state and disable setting
  function updateInputStyle(input, isRequired, shouldDisableIfNotReq) {
    if (shouldDisableIfNotReq) {
      input.style.opacity = isRequired ? '1' : '0.4';
      input.style.pointerEvents = isRequired ? '' : 'none';
    } else {
      input.style.opacity = '';
      input.style.pointerEvents = '';
    }
  }

  // Initialize when the DOM is fully loaded
  document.addEventListener('DOMContentLoaded', initFormFieldRequirements);
</script>

Creating the Make.com Scenario

1. Download the JSON blueprint below to get stated.

2. Navigate to Make.com and Create a New Scenario...

3. Click the small box with 3 dots and then Import Blueprint...

4. Upload your file and voila! You're ready to link your own accounts.

Need help with this MemberScript?

All Memberstack customers can ask for assistance in the 2.0 Slack. Please note that these are not official features and support cannot be guaranteed.

Join the 2.0 Slack
Version notes
Attributes
Description
Attribute
No items found.
Guides / Tutorials
No items found.
Tutorial
What is Memberstack?

Auth & payments for Webflow sites

Add logins, subscriptions, gated content, and more to your Webflow site - easy, and fully customizable.

Learn more