Tag Archives: Hubspot

Hubspot Embedded Form onFormReady & onFormSubmit

Hubspot is a fantastic tool for enabling custom forms on your website and saving that data into the Hubspot CRM for later actions. When using forms embedded on non-Hubspot websites I often find myself needing to stretch outside the scope of the default for the embed.

The Code

The code below you will see a few handy additions to the Hubspot form embed; onFormReady and onFormSubmit.

hbspt.forms.create({
     portalId: "xxxxxxx",
     formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
     css: "",
     onFormReady: function($form){
        // Stuff to do on after form is loaded             
     },
     onFormSubmit: function($form) {
        // Stuff do do before form is submitted 
     }
   }
});

On an embedded form, Hubspot dynamically loads some javascript and pulls in additional field data asynchronously after the page is loaded. If you need to add any manipulation to the load form or fields, you should do this in the onFormReady function.

Although documented in Hubspot’s documentation, if you are manipulating field .val() using jQuery there is a gotch that requires the addition of the .change() function.

jQuery('textarea[name="additional_order_comments"]').val('').change();

Without the above .change() function, Hubspot would submit the previous value of the field if was previously set and your CRM is set to pre-fill the fields.

The Issue

I had the need to create a form that used progressive fields, but also allowed me to present a comment form field that did not pre-fill the text area. As of this blog post, Hubspot does not include any option to turn off previous form values when using progressive fields.

The website needed to provide a field for additional comments and did not want to write an blank value for the field if it contained an existing value. So with some simple jQuery magic, the form now stores the form fields value, removes the field value on the form field, then re-applies the old value unless a new text value is entered.

hbspt.forms.create({
     portalId: "xxxxxxx",
     formId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
     css: "",
     onFormReady: function($form){
        textareaDefault =  jQuery('textarea[name="additional_order_comments"]').val();
jQuery('textarea[name="additional_order_comments"]').val('').change();                   
     },
     onFormSubmit: function($form) {
if(jQuery('textarea[name="additional_order_comments"]').val().length < 1){            jQuery('textarea[name="additional_order_comments"]').val(textareaDefault).change()
      }
   }
});

As mentioned previously, you will see the requirement for the .change() function in the jQuery selector above.

If this article helped you out, please leave a comment below, I always enjoying knowing I have helped others along their coding endeavors!