I’m trying to add some extra features to a Hubspot form in their CMS. The problem is I can’t change the code they generate. Is there a way to add stuff after their code to make it do what I want?
Here’s what their code looks like:
hbspt.forms.create({
portalId: '123456',
formId: 'abcdef-1234-5678-90gh-ijklmnopqrst'
});
I want to get the form data after it’s submitted. Ideally, it would look like this:
hbspt.forms.create({
portalId: '123456',
formId: 'abcdef-1234-5678-90gh-ijklmnopqrst',
onFormSubmit: function(data) {
console.log( $('input[name=firstname]').val() );
}
});
But since I can’t edit their code, I’m stuck. I tried adding my own script after theirs, but it didn’t work:
// Their code
<script>
hbspt.forms.create({
portalId: '123456',
formId: 'abcdef-1234-5678-90gh-ijklmnopqrst'
});
</script>
// My attempt
<script>
onFormSubmit: function(data) {
console.log( $('input[name=firstname]').val() );
}
</script>
Any ideas on how to make this work without changing their original code? Thanks!
I’ve dealt with a similar situation before, and there’s a workaround that might help you, Luna. Instead of trying to modify HubSpot’s code directly, you can use JavaScript’s ability to overwrite functions. Here’s what you can do:
Create a new script that runs after HubSpot’s, something like this:
<script>
(function() {
var oldCreate = hbspt.forms.create;
hbspt.forms.create = function(options) {
options.onFormSubmit = function(data) {
console.log($('input[name=firstname]').val());
// Add any other custom logic here
};
return oldCreate(options);
};
})();
</script>
This approach intercepts the create function, adds your custom onFormSubmit handler, and then calls the original function. It’s a bit more complex than direct modification, but it’s quite effective when you can’t change the original code. Just make sure this script loads after HubSpot’s, but before the form is created.
hey luna, i think u can use event listeners to catch the form submission. try something like this after their script:
document.addEventListener('hsFormSubmit', function(e) {
console.log($('input[name=firstname]').val());
});
this should grab the data without messing with hubspot’s code. lmk if it works!