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******@ex*****.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