Hubspot form: programmatically set field value via jQuery


#21

How do we do this with vanilla JS (no JQuery)? Or can someone link me to the answer if it’s already been given elsewhere?


#22

Hi guys and gals,

I had the same problem and fixed it by using the script in a different scope “jQuery” instead of “$”.

Working:
jQuery('input[name="firstname"]').val("Brian").change();

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


#23

I have the same issue, I'm trying to write on an input:
$(‘input[name=“firstname”]’).val(“damiano”).change();
but it doesn't:disappointed_relieved: work.


#24

Hi @Payman_Ferdowsali,

Is the form fully loaded before that script runs? Have you tried replacing $ with jQuery as mentioned above?


#25

Derek,
I used Document.load method from Javascrip to make sure it is loaded. I also both $ and JQuery. Apparantly the Document is loaded, but doesnt have all HTML5 attributes!


#26

Hi @Payman_Ferdowsali,

The Document.load method isn't the best event for this; that event fires when the DOM is loaded, but HubSpot forms are loaded dynamically by the form embed code. You should put the form field related code in the built-in onFormReady callback:


#27

Hi @Derek_Gervais,

I did so, but when I use onFormReady method, I get the error message saying:

shell.js:9 The onFormReady function in hbspt.forms.create requires jQuery. It was not run.

This is the code I have:

hbspt.forms.create({
portalId: '383XXXX',
formId: '6ae5c91f-67cf-40e7-bc53-XXXXXXXXXXXX',
onFormReady: function($form){
$('#firstname-6ae5c91f-67cf-40e7-bc53').val('Brian').change();
}
});


#28

Hi @Payman_Ferdowsali,

The error is accurate here; you need to include jQuery to get the full functionality of the form embed code. jQuery is included on HubSpot pages by default, but may not be included on yours.


#32

I included Jquery, but still getting the same error. This is my code:

<script src="jquery-3.3.1.min.js"></script>
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/shell.js"></script>
<script>
hbspt.forms.create({
portalId: '383xxxx',
formId: '6ae5c91f-67cf-40e7-bc53-14bbxxxxxxxx',      
onFormReady: function($form){
//$('#firstname-6ae5c91f-67cf-xxxx-xxxx').val('Brian').change();
document.getElementById("firstname-6ae5c91f-67cfxxxxxxxxxxxxx").value = "Brian";  
}
});

</script>

and this is the error I get:

The onFormReady function in hbspt.forms.create requires jQuery. It was not run.


#33

I found the solution:
1- I added jquery v 1.12.4 before hobspot form gets loaded.
2- Instead of using the js.hsforms.net/forms/shell.js which is in the default embedded code by hubspot, I used js.hsforms.net/forms/current.js.