Super Forms
  • Drag & Drop Form Builder for WordPress
  • Quick start
    • Installation
    • Registration
    • Starting your 15 day trial
    • Purchasing a license
    • Activating a license
    • First time setup
    • Secure file uploads
    • Creating a form
    • Adding form elements
    • Editing elements
    • Publishing your form
    • FAQ
  • Account
    • Dashboard
      • Your Invoices
      • Billing details
      • Your Licenses
      • E-mail Notification
      • Password reset
      • Cancel subscription
  • Common problems
    • Common problems
      • Email delivery problems
        • Why is my form not sending emails?
        • Why are emails going into spam folder/inbox?
      • File upload problems
      • Session expired
      • reCaptcha Troubleshooting – Fix “Not Loading” & Verification Errors
  • Elements
    • Layout elements
      • Column/Grid
      • Multi-part / step
    • Form elements
      • Calculator
      • Signature
      • File upload
      • Datepicker
      • Variable field
      • Dropdown
      • Text field
      • Autosuggest
      • Keywords
      • Radio button
      • Keyword Field
      • Button
      • Audio Recording (microphone)
    • HTML elements
      • Heading
      • HTML (raw)
      • Image
      • TinyMCE
      • Divider
      • Spacer
      • PDF page break
      • Google map element WordPress form
  • Features
    • Basic
      • Confirmations emails
      • Save Form Progression (continue later)
      • Build In Translation System
      • Populate form
      • Popups
      • Import & Export
      • Hide form after submitting
      • Hide or lock out user from your forms
      • Validation
    • Advanced
      • WordPress form with Google sheets dropdown
      • Custom registration form for WordPress
      • Custom login form for WordPress
      • Custom lost password form for WordPress
      • Update current logged in user
      • Secrets
      • Prevent duplicate entries
      • Lock & hide form
      • Password protect
      • Conditional Logic
      • Tags system
      • Address lookup/auto complete
      • Analytics Tracking
      • Conversion Tracking
      • Distance & Duration Calculation
      • If statements
      • Foreach loops
      • E-mail Reminders
      • Variable Fields
      • Form templates - Include elements into other forms - WordPress
      • Transferring data from one form to another
    • Integrations
      • PDF Generator
      • Listings
      • WooCommerce Checkout
        • Fixed price checkout
        • Dynamic price checkout
        • Variable product checkout (variations)
        • Replacing the "Add to cart" on a product page with a form
        • Hiding product from shop and order via custom form
      • PayPal
      • MailChimp
      • Mailster
      • Zapier
      • Stripe (BETA)
      • WooCommerce Instant Order (in progress)
  • Tutorials
    • WordPress Form to Google Sheet Integration
    • GDPR Consent / Terms agreement
    • How to update the plugin
    • Sending emails to specific department for WordPress contact forms
  • Example Forms for WordPress
    • Booking 24 hours ahead of time
  • Developers
    • Code Examples
      • Lookup City by Zipcode for your WordPress form
      • Audio Recording Field
      • Custom API Phone Number Validation for Your WordPress Form
      • Updating WordPress user meta data after login
      • Automatically redirecting to next step after displaying text or a progress bar
      • Dropdown with groups (categories)
      • Prevent form submission based on entered field values
      • Track form submissions with GTM (Google Tag Manager)
      • Tracking Multi-part steps with Google Analytics
      • Tracking Multi-part steps with GTM data layer (dataLayer.push)
      • Track form submissions with third party
      • Compare input field value with database value
      • Insert form data into a custom database table
      • Delete database row after contact entry is deleted in WordPress
      • Limited date availability (slots) for your WordPress booking form
      • Send submitted form data to another site
      • Exclude empty fields from emails
      • Execute custom JS when a column becomes conditionally visible
      • Toolset Plugin: Update comma separated string to Array for meta data saved via Front-end Posting
      • Toolset Plugin: Update file ID to file URL for meta data saved via Front-end Posting
      • Delete uploaded files after email has been send
      • Increase Cookie lifetime for client data such as [Form Progression]
      • Altering cookie secure and httponly parameters
      • Define fake cronjob to clear old client data if cronjob is disabled on your server
      • Define page language attribute based on page ID or URL
      • Define custom headers when doing a POST request
      • Change checkbox/radio layout to vertical on mobile devices
      • Show remaining available form submission allowed
      • Global fields / elements
      • Trim values of fields
      • Re-sending E-mails after editing entries via Listings for WordPress
      • Combine multiple field values into one column on Contact Entries page
      • Altering the attachments for E-mails via PHP code for WordPress
      • Generate dynamic columns with dates based on user selected date from Datepicker element
      • Hide `eye` icon from Listings row based on user role
      • Variable product checkout based on variation SKU
    • Data storage
    • BETA version
  • Changelog
  • Support
Powered by GitBook
On this page
  • Demo:
  • Form code:
  • JavaScript code:
  1. Developers
  2. Code Examples

Generate dynamic columns with dates based on user selected date from Datepicker element

This is an example form that allows a user to select a date from a Datepicker element. After which a dynamic column with fields will be added for all following days.

PreviousAltering the attachments for E-mails via PHP code for WordPressNextHide `eye` icon from Listings row based on user role

Last updated 23 days ago

Below is an image of an example where the users selects a date, after which the script automatically adds 3 with the 2 dates that follow the selected date from the


  • Get the

  • Get the


Demo:

Form code:

Copy paste the below form code on your [CODE] tab as your Form Elements

[
    {
        "tag": "date",
        "group": "form_elements",
        "data": {
            "name": "dynamic_column_datepicker",
            "email": "Date:",
            "placeholder": "Select a date",
            "icon": "calendar",
            "work_days": "true",
            "weekends": "true"
        }
    },
    {
        "tag": "column",
        "group": "layout_elements",
        "inner": [
            {
                "tag": "heading",
                "group": "html_elements",
                "data": {
                    "title": "Monday 5th May",
                    "size": "h3",
                    "heading_size": "14"
                }
            },
            {
                "tag": "dropdown",
                "group": "form_elements",
                "data": {
                    "name": "option",
                    "email": "Option (Monday 5th May):",
                    "dropdown_items": [
                        {
                            "checked": "false",
                            "label": "First choice",
                            "value": "first_choice"
                        },
                        {
                            "checked": "false",
                            "label": "Second choice",
                            "value": "second_choice"
                        },
                        {
                            "checked": "false",
                            "label": "Third choice",
                            "value": "third_choice"
                        }
                    ],
                    "placeholder": "- select a option -",
                    "icon": "caret-square-down;far"
                }
            },
            {
                "tag": "dropdown",
                "group": "form_elements",
                "data": {
                    "name": "reason",
                    "email": "Reason (Monday 5th May):",
                    "dropdown_items": [
                        {
                            "checked": "false",
                            "label": "First choice",
                            "value": "first_choice"
                        },
                        {
                            "checked": "false",
                            "label": "Second choice",
                            "value": "second_choice"
                        },
                        {
                            "checked": "false",
                            "label": "Third choice",
                            "value": "third_choice"
                        }
                    ],
                    "placeholder": "- select a option -",
                    "icon": "caret-square-down;far"
                }
            }
        ],
        "data": {
            "duplicate": "enabled",
            "duplicate_limit": "7"
        }
    }
]

JavaScript code:

JavaScript code, which you can place on the page where your form is located (or you could add it under Super Forms > Settings > Custom JS )

Place the below JavaScript code on the page where your form is located

(or add it under Super Forms > Settings > Custom JS ), make sure to adjust it according to your form field names. For example, the code below had hardcoded field name references to Datepicker field nameddynamic_column_datepicker and Dropdown fields named option and reason .

(function(){
	var timer2,timer = setInterval(function() {
	    if (super_common_i18n && SUPER) {
	        console.log(super_common_i18n.dynamic_functions.after_field_change_blur_hook);
	        clearInterval(timer);
	        super_common_i18n.dynamic_functions.after_field_change_blur_hook.push({
	            name: 'f4d_generate_week_columns'
	        });
	        var currentDateValue = '';
	        if(document.querySelector('.super-form input[name="dynamic_column_datepicker"]')){
	        	currentDateValue = document.querySelector('.super-form input[name="dynamic_column_datepicker"]').value;
	    	}
	        SUPER.f4d_generate_week_columns = function(args) {
	            if (!args || !args.el || args.el.name !== 'dynamic_column_datepicker') return;
				if(!timer2){
					timer2 = setInterval(function() {
			            clearInterval(timer2);
			            timer2 = null;
			            if(currentDateValue!==args.el.value){
			            	currentDateValue = args.el.value;
			                const form = SUPER.get_frontend_or_backend_form({ el: args.el });
			                if (!form) return; 
			                clearDynamicColumnsExceptFirst(form);
							const selected = args.el.value;
			                const [day, month, year] = selected.split('-').map(Number);
			                const baseDate = new Date(year, month - 1, day);
			                if (isNaN(baseDate)) return;
			                addColumnsWithDates(baseDate, form);
			            }
					}, 150);
				}
	        }
	    }
	}, 150); 
    function formatHeading(date) {
        const options = { weekday: 'long', month: 'long' };
        const weekdayMonth = date.toLocaleDateString('en-GB', options);
        const day = date.getDate();
        const suffix = (d => {
            if (d > 3 && d < 21) return 'th';
            switch (d % 10) {
                case 1: return 'st';
                case 2: return 'nd';
                case 3: return 'rd';
                default: return 'th';
            }
        })(day);
        return `${weekdayMonth.split(' ')[0]} ${day}${suffix} ${weekdayMonth.split(' ')[1]}`;
    }
    function clearDynamicColumnsExceptFirst(form) {
        const columns = form.querySelectorAll('.super-duplicate-column-fields');
        const firstColumn = columns[0];
        SUPER.init_clear_form({ form: form, clone: firstColumn });
		for (let i = columns.length-1; i >= 1; i--){
            const deleteBtn = columns[i].querySelector('.super-delete-duplicate');
            deleteBtn.click();
        }
    }
    function updateHeading(container, dateObj) {
        var formattedDate = formatHeading(dateObj);
        var el = container.querySelector('.super-heading-title h3');
		if (el) el.innerHTML = formattedDate;
		el = container.querySelector('.super-shortcode-field[data-oname="option"]');
		label = 'Option ('+formattedDate+')';
		if (el) el.dataset.email = label;
		el = container.querySelector('.super-shortcode-field[data-oname="reason"]');
		label = 'Reason ('+formattedDate+')';	
		if (el) el.dataset.email = label;
	}
    function addColumnsWithDates(baseDate, form) {
        const allContainers = () => form.querySelectorAll('.super-duplicate-column-fields');
        // First column
        const firstColumn = allContainers()[0];
        updateHeading(firstColumn, baseDate);
        const addBtn = firstColumn.querySelector('.super-add-duplicate');
        if (!addBtn) return;
        for (let i = 1; i < 7; i++) {
            const prevCount = allContainers().length;
            addBtn.click();
            // Wait until new column is actually added
            let retries = 0;
            while (allContainers().length <= prevCount && retries < 20) {
                retries++;
            }
            const newColumns = allContainers();
            const newColumn = newColumns[newColumns.length - 1];
            const newDate = new Date(baseDate);
            newDate.setDate(baseDate.getDate() + i);
            updateHeading(newColumn, newDate);
        }
    }
})();
Datepicker element
Form demo code
JavaScript code
Dynamic columns
Form with dynamic columns added based on selected date