← All Scripts

#10 - Hide Element If Custom Field Is Blank v0.2

Check if a member has filled out a custom field, and hide elements from the page if they have not.

View demo

<!-- 💙 MEMBERSCRIPT #10 v0.2 💙 HIDE ELEMENTS IF CUSTOM FIELD IS BLANK -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  // Get the `_ms-mem` object from the local storage
  const msMem = JSON.parse(localStorage.getItem('_ms-mem'));

  // Get all the elements that have the `ms-code-customfield` attribute
  const elements = document.querySelectorAll('[ms-code-customfield]');

  // Iterate over each element
  elements.forEach(element => {
    // Get the value of the `ms-code-customfield` attribute
    const customField = element.getAttribute('ms-code-customfield');

    // If customField starts with '!', we invert the logic
    if (customField.startsWith('!')) {
      const actualCustomField = customField.slice(1); // remove the '!' from the start

      // If the user does have the custom field, remove the element from the DOM
      if (msMem.customFields && msMem.customFields[actualCustomField]) {
        element.parentNode.removeChild(element);
      }
    } else {
      // Check if the user has the corresponding custom field in Memberstack
      if (!msMem.customFields || !msMem.customFields[customField]) {
        // If the user does not have the custom field, remove the element from the DOM
        element.parentNode.removeChild(element);
      }
    }
  });
});
</script>
Description
Attribute
Content | Hide if Data is Missing
Hide this element if the corresponding custom field is empty.
ms-code-customfield
MS_FIELD_ID
MS_FIELD_ID

v0.2 - Ability to also HIDE element

Added the possibility to not only show the element to users who have that custom field filled out, but also to hide it for them.

This is useful for use cases where, for example, you want to show a "complete your profile" form to people who do not have the "onboarding" field filled out.

Button Text