Populate Divi Form Fields with URL Parameters

Advanced

Javascript

Form Builder

Details

This JavaScript code dynamically populates form fields based on URL parameters in a web page using the Divi Form Builder. It ensures that specific form fields are pre-filled with values from the URL, improving user experience and data accuracy. Additionally, if a URL parameter does not correspond to a valid field ID, an error message is populated in a hidden field within the form for backend processing or logging. This will even work with your hidden field types in Divi Form Builder.

For Example:

https://yourwebsite.com/yourformpage?f_name=John%20Doe&f_email=jo******@*****le.com

This URL will populate Divi Form Builder fields with the Field ID’s f_name and f_email with the values passed in the URL.

Snippets Demo

Divi Form Builder URL Parameter

Code

1

Description:
Set Field IDs in Divi Form Builder: Ensure that each form field you want to populate has a Field ID that matches the names used in the fields array in the JavaScript code. For example, set Field ID to f_name for the Name field and f_hidden_1 for the hidden field. Update the Fields Array: Modify the fields array in the JavaScript code to include the Field IDs of all the fields you want to populate. Example: var fields = ['f_name', 'f_email', 'f_phone']. Give Your Form the Correct ID: Ensure your Divi Form Module has an id attribute that matches the ID used in the JavaScript code. For example: "de_paramater_form"

Language: Javascript

Where to add: Divi Code Module

                          jQuery(document).ready(function($) {
    // Function to get URL parameters by name
    function getUrlParameter(sParam) {
      var sPageURL = window.location.search.substring(1), // Get the query string part of the URL
        sURLVariables = sPageURL.split('&'), // Split the query string into individual parameters
        sParameterName,
        i;

      // Loop through each parameter to find the one matching sParam
      for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('='); // Split parameter name and value

        // If the parameter name matches sParam, return the decoded value
        if (sParameterName[0] === sParam) {
          return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
      }
      return false; // Return false if the parameter is not found
    }

    // Define the form fields you want to populate from URL parameters, these should match the Field ID you set in the module settings
    var fields = ['f_name', 'f_hidden_1'];

    // Track unmatched URL parameters
    var unmatchedParams = [];

    // Get all URL parameters
    var urlParams = new URLSearchParams(window.location.search);

    // Loop through each URL parameter
    urlParams.forEach((value, key) => {
      if (fields.includes(key)) {
        $('#' + key).val(value); // Set the form field's value if it matches a field ID
      } else {
        unmatchedParams.push(key); // Track the unmatched parameters
      }
    });

    // Populate the hidden field with unmatched parameters if any
    if (unmatchedParams.length > 0) {
      var errorMessage = 'The following URL parameters did not match any field IDs: ' + unmatchedParams.join(', ');
      $('#f_hidden_1').val(errorMessage);
    }

    // Store the original URL validation method
    let old_url = jQuery.validator.methods.url;

    // Overwrite the 'url' method of the validator to include URLs without 'http://' or 'https://'
    jQuery.validator.addMethod('url', function(value, element) {
      // Try the original validator method
      if (old_url.call(this, value, element)) {
        return true;
      }

      // Try with 'http://' prepended if the original value does not pass
      if (value && !value.startsWith('http://') && !value.startsWith('https://')) {
        return old_url.call(this, 'http://' + value, element);
      }

      // Fallback to false if neither check passes
      return false;
    }, 'Please enter a valid URL.');

    // Initialize form validation
    $('#de_paramater_form').validate({
      normalizer: function(value) {
        return $.trim(value); // Trim the value of every element
      },
      errorPlacement: function(error, element) {
        var message_position = element.attr('data-required_position');
        if (message_position == 'top') {
          element.before(error); // Place error message before the element if position is 'top'
        } else {
          element.after(error); // Default error placement after the element
        }
      }
    });

    // Initialize autocomplete fields if they exist
    if ($('.de_fb_autocomplete').length > 0 && typeof init_autocomplete_fields == 'function') {
      init_autocomplete_fields();
    }
  });

  // Prevent form resubmission on page reload
  if (window.history.replaceState) {
    window.history.replaceState(null, null, window.location.href);
  }
                    

Related Snippets

Explore more from Divi Engine

Divi Form Builder

Divi Form Builder

From simple contact forms to complex frontend post or product creation, Divi Form Builder has you covered.

Divi Form Builder
Find out more
Divi Machine

Divi Machine

Build complex websites that displays dynamic fields you can filter, search and so much more with the Divi Builder.      

Divi Machine
Find out more
Divi BodyCommerce

Divi BodyCommerce

A versatile toolkit for developers using Divi and WooCommerce together, designed to boost your e-commerce site and achieve greater conversion rates.    

Divi BodyCommerce
Find out more
Divi Handoff

Divi Handoff

Let clients update content without touching the Divi Builder. Design layouts once, connect them to Flexible Content fields, and give editors simple forms for text, images, and sections.

Divi Handoff
Find out more
Divi Loop Extender

Divi Loop Extender

Unlock the Full Power of Divi 5 Loop Builder Add advanced sorting, filtering, and relationship logic right inside the Visual Builder.

Divi Loop Extender
Find out more
Divi Membership

Divi Membership

Monetize your Divi websites by transforming them into membership sites with seamless subscription management, user-friendly interfaces, and customizable membership tiers.

Divi Membership
Find out more
Divi Machine Accounts

Divi Machine Accounts

Build an account area for your customers to edit their details, access wishlist, submitted posts and more. *Note: Requires Divi Machine installed and active

Divi Machine Accounts
Find out more
Divi Ajax Filter

Divi Ajax Filter

Filter WooCommerce, Posts & Custom Posts without reloading the page.    

Divi Ajax Filter
Find out more
Divi Mobile

Divi Mobile

Divi Mobile helps you create beautiful looking mobile menus without having to code.

Divi Mobile
Find out more
Divi Nitro

Divi Nitro

Give your Divi website that extra boost of speed with our Divi Nitro plugin to enhance your customer's experience.

Divi Nitro
Find out more
Divi Protect

Divi Protect

Password protect the content of your Divi website with our Divi Protect plugin. Keep unwanted eyes out!

Divi Protect
Find out more
Divi Mega Menu

Divi Mega Menu

Create stunning, responsive, and content-rich mega menus using the Divi Builder you already know. No coding required.  

Divi Mega Menu
Find out more