Adding Custom Attributes to Hubspot Form Elements

Hey everyone! I’m working on a Hubspot project and I’m trying to figure out how to add custom attributes to the form elements Hubspot creates. Is there a good way to do this? I’m especially interested in adding attributes to the <form> tag itself.

For example, I want to end up with something like this:

<form id="my-hubspot-form" data-custom="some-value"></form>

I’m hoping for a static solution if possible, since I need this for form analytics. Any ideas or tips would be super helpful! Thanks in advance for your suggestions!

As someone who’s worked extensively with HubSpot forms, I can offer another perspective. While modifying the embed code or using JavaScript are valid approaches, I’ve found success using HubSpot’s Form API. It provides a cleaner, more maintainable solution for adding custom attributes.

Here’s the gist:

  1. Create your form in HubSpot as usual.
  2. Use the Form API to render the form on your page.
  3. In the API call, you can specify custom attributes for the form.

It looks something like this:

hbspt.forms.create({
    portalId: 'your-portal-id',
    formId: 'your-form-id',
    formInstanceId: 'my-hubspot-form',
    css: '',
    target: '#form-container',
    formData: {
        customAttributes: {
            'data-custom': 'some-value'
        }
    }
});

This method gives you full control over form attributes without risking future compatibility issues. It’s been my go-to for integrating custom analytics and tracking.

yo flyingeagle, another option is using javascript to modify the form after it loads. you can use MutationObserver to watch for when hubspot adds the form to the page, then add your custom attributes. it’s pretty flexible and won’t break if hubspot changes their embed code. give it a shot!

I’ve found a more flexible approach to this challenge. Instead of modifying the embed code directly, you can use JavaScript to add custom attributes after the form loads. This method is less likely to break when HubSpot updates their code.

Here’s a basic example:

window.addEventListener('message', function(event) {
    if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
        var form = document.querySelector('form.hs-form');
        if (form) {
            form.setAttribute('data-custom', 'some-value');
        }
    }
});

This approach is more robust and allows you to add multiple attributes dynamically. It also works well with form analytics tools.

hey flyingeagle, i’ve dealt with this before. you can use the hubspot form embed code and add your custom attributes directly to the tag there. just make sure to keep the existing attributes intact. it’s a bit hacky but works for static stuff. good luck with your analytics!