Skip to content

Instantly share code, notes, and snippets.

@robertainslie
Last active January 4, 2024 19:47
Show Gist options
  • Save robertainslie/32d786d7254ec7bc6cbbff3d1e292cd4 to your computer and use it in GitHub Desktop.
Save robertainslie/32d786d7254ec7bc6cbbff3d1e292cd4 to your computer and use it in GitHub Desktop.

Sometimes, a customer might have data being loaded programmatically into a page and want that data to write to form fields. Because HubSpot Forms are generated programmatically with React, there need to be two considerations in your code that make setting fields programmatically more difficult:

  1. The data must be inserted after the form has finished loading
  2. Data that is inserted programmatically must have a js "change" event fired on the field in order to propagate the change into the React data layer

These two considerations are handled separately.

Inserting form data after form load

There are two methods to handle this - one including jQuery and one using vanilla javascript

  1. Using vanilla JS "load" event on the window
window.addEventListener('load', (event) => {
  console.log('page is fully loaded');
  //add the your custom script here, the HubSpot Form should be loaded
});
  1. Using jQuery's window.load function
$(window).load((event) => {
  //add your custom script here, the HubSpot Form should be loaded
});

Firing a "change" event after setting fields

Similarly, let's assume that after your window load event, your goal is to set a field programmatically with javascript. To propagate this data into HubSpot Form's React data layer, there must be a javascript 'change' event. This essentially tells HubSpot Forms that data has been input into the field, just not by an actual website visitor.

This change event can be triggered using vanilla JS or jQuery.

The jQuery .change() event is documented on HubSpot's Developer Site in the Forms API section about customizing the embed code:

   $('input[value="checkbox_1"]').prop('checked', true).change();

    $('input[name="firstname"]').val('Brian').change(); 

With vanilla JS using the "dispatchEvent" method:

const changeEvent = new Event('change')

var companyNameField = document.querySelector('[name="company"]')
companyNameField.value = "HubSpot"
companyNameField.dispatchEvent(changeEvent)

Combine these two methods in one solution The above example provides a one-off solution to setting a single field. This leads to a few questions:

What happens if you want to set multiple fields at once? What happens if the incoming data is actually called from another system on page load?

Well, I wrote this JS function to handle these scenarios:

The below solution wraps the bulk of the call in a vanilla JS window load. The function that does the data setting takes two objects: a field mapping object and a data object The field mapping object expects the field name from the incoming data object as the "key" and the HubSpot form field name as the "value". It ignores any data key that doesn't have a field on the page.

function writeFormFieldData (mappingsObject,dataObject) {

        var mappingsObject = mappingsObject
        const changeEvent = new Event('change');
        var mappedFieldsArray = Object.keys(mappingsObject)
        var returnedDataArray = Object.keys(dataObject)
        var fieldsToUpdate = mappedFieldsArray.filter(item => returnedDataArray.includes(item))
        fieldsToUpdate.map(function (dataObjectFieldName){
            var hsFieldName = mappingsObject[dataObjectFieldName]
            fieldToUpdate = document.querySelector(`[name="${hsFieldName}"]`)
            if (fieldToUpdate == null) {
                console.log('invalid field name')
            }
            else{
                fieldToUpdate.value = dataObject[dataObjectFieldName]
                fieldToUpdate.dispatchEvent(changeEvent)
            }
        })
    }
//sample data object

const data = {
    companyAddress: "1 Apple Park Way",
    companyCity: "Cupertino",
    companyCountry: "USA",
    companyCounty: "Santa Clara",
    companyMsa: "San Jose,CA",
    companyName: "Apple Inc.",
    companyState: "CA",
    phone: "companyTelephone",
    companyZip5: "95014",
    employeesAtLocationNum: "2000",
    employeesInAllLocations: "Large",
    employeesInAllLocationsNum: "132000"
}

//sample mapping object

var fieldMap = {

    duns: "duns_number",
    companyName: "company",
    companyAddress: "address",
    companyCity: "city",
    companyState: "state",
    companyZip5: "zip",
    companyCountry: "country",
    naicsCodes: "naics_code__c",
    sicCodes: "sic_code__c",
    employeesAtLocationNum: "numberofemployees",
    phone:"companyTelephone"
}
//call function after page load, including 
//the field mapping object and data object



window.addEventListener('load', (event) => {
  writeFormFieldData(fieldMap,data)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment