#198 - Add Individual Items to Data Tables v0.1

Let members save simple values, grouped fields, or growing lists into Data Tables.

View demo

<!-- 💙 MEMBERSCRIPT #198 v0.1 💙 - ADD INDIVIDUAL ITEMS TO DATA TABLES -->
<script>
document.addEventListener("DOMContentLoaded", function() {
  const forms = document.querySelectorAll('[data-ms-code="form1"]');
  
  // Helper function to show loading state
  function setLoadingState(form, isLoading) {
    const submitButton = form.querySelector('button[type="submit"], input[type="submit"], button:not([type])');
    const originalButtonText = submitButton ? submitButton.textContent || submitButton.value : '';
    
    if (submitButton) {
      submitButton.disabled = isLoading;
      submitButton.style.opacity = isLoading ? '0.6' : '1';
      submitButton.style.cursor = isLoading ? 'not-allowed' : 'pointer';
      
      if (isLoading) {
        submitButton.dataset.originalText = originalButtonText;
        submitButton.textContent = 'Saving...';
        if (submitButton.value) submitButton.value = 'Saving...';
      } else {
        const original = submitButton.dataset.originalText || originalButtonText;
        submitButton.textContent = original;
        if (submitButton.value) submitButton.value = original;
        delete submitButton.dataset.originalText;
      }
    }
    
    // Disable all inputs during save
    const inputs = form.querySelectorAll('input, textarea, select, button');
    inputs.forEach(input => {
      if (input !== submitButton) {
        input.disabled = isLoading;
      }
    });
  }
  
  // Helper function to show success message
  function showSuccessMessage(form, message) {
    // Remove any existing messages
    const existingMessage = form.querySelector('[data-ms-code="success-message"]');
    if (existingMessage) existingMessage.remove();
    
    // Create success message element
    const successMsg = document.createElement('div');
    successMsg.setAttribute('data-ms-code', 'success-message');
    successMsg.textContent = message || 'Saved successfully!';
    successMsg.style.cssText = 'padding: 12px; background-color: #10b981; color: white; border-radius: 6px; margin-top: 12px; font-size: 14px; text-align: center; animation: fadeIn 0.3s ease-in;';
    
    // Add fade-in animation if not exists
    if (!document.getElementById('ms198-styles')) {
      const style = document.createElement('style');
      style.id = 'ms198-styles';
      style.textContent = `
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(-10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes fadeOut {
          from { opacity: 1; }
          to { opacity: 0; }
        }
      `;
      document.head.appendChild(style);
    }
    
    form.appendChild(successMsg);
    
    // Remove message after 3 seconds
    setTimeout(() => {
      successMsg.style.animation = 'fadeOut 0.3s ease-out';
      setTimeout(() => successMsg.remove(), 300);
    }, 3000);
  }
  
  // Helper function to show error message
  function showErrorMessage(form, message) {
    const existingMessage = form.querySelector('[data-ms-code="error-message"]');
    if (existingMessage) existingMessage.remove();
    
    const errorMsg = document.createElement('div');
    errorMsg.setAttribute('data-ms-code', 'error-message');
    errorMsg.textContent = message || 'Failed to save. Please try again.';
    errorMsg.style.cssText = 'padding: 12px; background-color: #ef4444; color: white; border-radius: 6px; margin-top: 12px; font-size: 14px; text-align: center; animation: fadeIn 0.3s ease-in;';
    
    form.appendChild(errorMsg);
    
    setTimeout(() => {
      errorMsg.style.animation = 'fadeOut 0.3s ease-out';
      setTimeout(() => errorMsg.remove(), 5000);
    }, 5000);
  }
  
  forms.forEach(form => {
    const dataType = form.getAttribute("data-ms-code-table-type");
    const tableName = form.getAttribute("data-ms-code-table");
    const memberField = form.getAttribute("data-ms-code-member-field") || 'member';
    const storageKey = form.getAttribute("data-ms-code-storage-key") || "memberDataTable";

    // Disable Webflow form submission
    form.setAttribute('action', 'javascript:void(0);');
    form.setAttribute('method', 'post');
    form.setAttribute('novalidate', 'novalidate');
    
    // Prevent any Webflow form handlers
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    }, { capture: true, passive: false });

    form.addEventListener('submit', async function(event) {
      event.preventDefault(); // Prevent the default form submission
      event.stopPropagation(); // Stop event bubbling
      event.stopImmediatePropagation(); // Stop other handlers

      // Set loading state
      setLoadingState(form, true);
      
      // Remove any existing messages
      const existingMessages = form.querySelectorAll('[data-ms-code="success-message"], [data-ms-code="error-message"]');
      existingMessages.forEach(msg => msg.remove());

      // Get Memberstack instance
      const memberstack = window.$memberstackDom;
      if (!memberstack) {
        setLoadingState(form, false);
        showErrorMessage(form, 'Memberstack not initialized');
        return;
      }

      // Validate required attributes
      if (!tableName) {
        setLoadingState(form, false);
        showErrorMessage(form, 'Table name required. Add data-ms-code-table attribute to form.');
        return;
      }

      // Get current member
      const memberResult = await memberstack.getCurrentMember();
      const member = memberResult?.data || memberResult;
      if (!member?.id) {
        setLoadingState(form, false);
        showErrorMessage(form, 'Please log in to save data');
        return;
      }

      if (dataType === "group") {
        // Create a single record with multiple fields (group of key-value pairs)
        const inputs = form.querySelectorAll('[data-ms-code-table-name]');
        const recordData = {
          [memberField]: member.id // Link record to member
        };

        inputs.forEach(input => {
          const fieldName = input.getAttribute('data-ms-code-table-name');
          const fieldValue = input.value;
          if (fieldName) {
            recordData[fieldName] = fieldValue || null;
          }
        });

        try {
          await memberstack.createDataRecord({
            table: tableName,
            data: recordData
          });
          setLoadingState(form, false);
          showSuccessMessage(form, 'Saved successfully!');
          // Trigger #199 to sync localStorage immediately
          if (window.ms199SyncDataTable) {
            window.ms199SyncDataTable();
          }
          // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
          if (window.ms200UpdateLocalStorage) {
            window.ms200UpdateLocalStorage(tableName, storageKey, 500);
          }
        } catch (error) {
          // Try with member as object if direct ID fails
          try {
            const retryData = { ...recordData };
            retryData[memberField] = { id: member.id };
            await memberstack.createDataRecord({
              table: tableName,
              data: retryData
            });
            setLoadingState(form, false);
            showSuccessMessage(form, 'Saved successfully!');
            // Trigger #199 to sync localStorage immediately
            if (window.ms199SyncDataTable) {
              window.ms199SyncDataTable();
            }
            // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
            if (window.ms200UpdateLocalStorage) {
              window.ms200UpdateLocalStorage(tableName, storageKey, 500);
            }
          } catch (retryError) {
            setLoadingState(form, false);
            showErrorMessage(form, 'Failed to save. Please try again.');
          }
        }

      } else if (dataType === "array") {
        // Array type: Append items to existing record or create new one
        // Items are stored as JSON array in a TEXT field
        const arrayFieldName = form.getAttribute('data-ms-code-array-field');
        if (!arrayFieldName) {
          setLoadingState(form, false);
          showErrorMessage(form, 'Array field name required. Add data-ms-code-array-field attribute to form.');
          return;
        }
        const inputs = form.querySelectorAll('[data-ms-code-table-name]');
        
        // Collect all input values into an object
        const newItem = {};
        inputs.forEach(input => {
          const fieldName = input.getAttribute('data-ms-code-table-name');
          const fieldValue = input.value;
          if (fieldName && fieldValue.trim()) {
            newItem[fieldName] = fieldValue;
          }
        });

        if (Object.keys(newItem).length === 0) {
          setLoadingState(form, false);
          showErrorMessage(form, 'Please fill in at least one field');
          return;
        }

        try {
          // Query for existing record for this member
          let existingRecord = null;
          
          // Try querying with direct member ID
          try {
            const queryResult = await memberstack.queryDataRecords({
              table: tableName,
              query: {
                where: { [memberField]: { equals: member.id } },
                take: 100
              }
            });
            
            // Check different possible result structures
            const records = queryResult?.data?.records || queryResult?.data || [];
            // Filter records by member ID
            for (const record of records) {
              const recordMember = record.data?.[memberField];
              if (recordMember === member.id || recordMember?.id === member.id) {
                existingRecord = record;
                break;
              }
            }
          } catch (queryError) {
            // If query fails, try to get all records and filter manually
            try {
              const queryResult = await memberstack.queryDataRecords({
                table: tableName,
                query: {
                  take: 100
                }
              });
              
              const records = queryResult?.data?.records || queryResult?.data || [];
              // Filter records by member ID
              for (const record of records) {
                const recordMember = record.data?.[memberField];
                if (recordMember === member.id || recordMember?.id === member.id) {
                  existingRecord = record;
                  break;
                }
              }
            } catch (queryError2) {
              // No existing record found, will create new one
            }
          }

          if (existingRecord) {
            // Update existing record - append to array
            const existingData = existingRecord.data || {};
            let itemsArray = [];
            
            // Parse existing array if it exists
            if (existingData[arrayFieldName]) {
              try {
                itemsArray = typeof existingData[arrayFieldName] === 'string' 
                  ? JSON.parse(existingData[arrayFieldName]) 
                  : existingData[arrayFieldName];
              } catch (parseError) {
                itemsArray = [];
              }
            }
            
            // Add new item to array
            itemsArray.push(newItem);
            
            // Update the record
            try {
              await memberstack.updateDataRecord({
                recordId: existingRecord.id,
                data: {
                  [arrayFieldName]: JSON.stringify(itemsArray)
                }
              });
              setLoadingState(form, false);
              showSuccessMessage(form, 'Item added successfully!');
              // Trigger #199 to sync localStorage immediately
              if (window.ms199SyncDataTable) {
                window.ms199SyncDataTable();
              }
              // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
              if (window.ms200UpdateLocalStorage) {
                window.ms200UpdateLocalStorage(tableName, storageKey, 500);
              }
            } catch (updateError) {
              // Try with member as object if direct ID fails
              const updateData = {
                [arrayFieldName]: JSON.stringify(itemsArray)
              };
              await memberstack.updateDataRecord({
                recordId: existingRecord.id,
                data: updateData
              });
              setLoadingState(form, false);
              showSuccessMessage(form, 'Item added successfully!');
              // Trigger #199 to sync localStorage immediately
              if (window.ms199SyncDataTable) {
                window.ms199SyncDataTable();
              }
              // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
              if (window.ms200UpdateLocalStorage) {
                window.ms200UpdateLocalStorage(tableName, storageKey, 500);
              }
            }
          } else {
            // Create new record with first item in array
            const recordData = {
              [memberField]: member.id,
              [arrayFieldName]: JSON.stringify([newItem])
            };

            try {
              await memberstack.createDataRecord({
                table: tableName,
                data: recordData
              });
              setLoadingState(form, false);
              showSuccessMessage(form, 'Saved successfully!');
              // Trigger #199 to sync localStorage immediately
              if (window.ms199SyncDataTable) {
                window.ms199SyncDataTable();
              }
              // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
              if (window.ms200UpdateLocalStorage) {
                window.ms200UpdateLocalStorage(tableName, storageKey, 500);
              }
            } catch (error) {
              // Try with member as object if direct ID fails
              const retryData = { ...recordData };
              retryData[memberField] = { id: member.id };
              await memberstack.createDataRecord({
                table: tableName,
                data: retryData
              });
              setLoadingState(form, false);
              showSuccessMessage(form, 'Saved successfully!');
              // Trigger #199 to sync localStorage immediately
              if (window.ms199SyncDataTable) {
                window.ms199SyncDataTable();
              }
              // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
              if (window.ms200UpdateLocalStorage) {
                window.ms200UpdateLocalStorage(tableName, storageKey, 500);
              }
            }
          }
        } catch (error) {
          setLoadingState(form, false);
          showErrorMessage(form, 'Failed to save. Please try again.');
        }

      } else {
        // Basic type: Create a single record with one field
        const inputs = form.querySelectorAll('[data-ms-code-table-name]');
        if (inputs.length === 0) {
          setLoadingState(form, false);
          showErrorMessage(form, 'No input fields found');
          return;
        }

        const input = inputs[0];
        const fieldName = input.getAttribute('data-ms-code-table-name');
        const fieldValue = input.value;

        const recordData = {
          [memberField]: member.id,
          [fieldName]: fieldValue || null
        };

        try {
          await memberstack.createDataRecord({
            table: tableName,
            data: recordData
          });
          setLoadingState(form, false);
          showSuccessMessage(form, 'Saved successfully!');
          // Trigger #199 to sync localStorage immediately
          if (window.ms199SyncDataTable) {
            window.ms199SyncDataTable();
          }
          // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
          if (window.ms200UpdateLocalStorage) {
            window.ms200UpdateLocalStorage(tableName, storageKey, 500);
          }
        } catch (error) {
          // Try with member as object if direct ID fails
          try {
            const retryData = { ...recordData };
            retryData[memberField] = { id: member.id };
            await memberstack.createDataRecord({
              table: tableName,
              data: retryData
            });
            setLoadingState(form, false);
            showSuccessMessage(form, 'Saved successfully!');
            // Trigger #199 to sync localStorage immediately
            if (window.ms199SyncDataTable) {
              window.ms199SyncDataTable();
            }
            // Trigger #200 to update latest record in localStorage (with small delay to ensure save)
            if (window.ms200UpdateLocalStorage) {
              window.ms200UpdateLocalStorage(tableName, storageKey, 500);
            }
          } catch (retryError) {
            setLoadingState(form, false);
            showErrorMessage(form, 'Failed to save. Please try again.');
          }
        }
      }

      // Reset the input values
      const inputs = form.querySelectorAll('[data-ms-code-table-name]');
      inputs.forEach(input => {
        input.value = "";
      });
      
      return false; // Prevent any further form submission
    }, { capture: true });
  });
});
</script>

Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

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

"We've been using Memberstack for a long time, and it has helped us achieve things we would have never thought possible using Webflow. It's allowed us to build platforms with great depth and functionality and the team behind it has always been super helpful and receptive to feedback"

Jamie Debnam
39 Digital

"Been building a membership site with Memberstack and Jetboost for a client. Feels like magic building with these tools. As someone who’s worked in an agency where some of these apps were coded from scratch, I finally get the hype now. This is a lot faster and a lot cheaper."

Félix Meens
Webflix Studio

"One of the best products to start a membership site - I like the ease of use of Memberstack. I was able to my membership site up and running within a day. Doesn't get easier than that. Also provides the functionality I need to make the user experience more custom."

Eric McQuesten
Health Tech Nerds
Off World Depot

"My business wouldn't be what it is without Memberstack. If you think $30/month is expensive, try hiring a developer to integrate custom recommendations into your site for that price. Incredibly flexible set of tools for those willing to put in some minimal efforts to watch their well put together documentation."

Riley Brown
Off World Depot

"The Slack community is one of the most active I've seen and fellow customers are willing to jump in to answer questions and offer solutions. I've done in-depth evaluations of alternative tools and we always come back to Memberstack - save yourself the time and give it a shot."

Abbey Burtis
Health Tech Nerds
Slack

Need help with this MemberScript? Join our Slack community!

Join the Memberstack community Slack and ask away! Expect a prompt reply from a team member, a Memberstack expert, or a fellow community member.

Join our Slack