APIs & Integrations

mswinimer
Member | Elite Partner
Member | Elite Partner

Can I create a hubspot form with a javascript function once needed.

I have a page that only shows my form after completing a quiz (and there are 3 different forms depending on your answers). I want to run the hbspt.forms.create({...})  snippet from within the function which sets innerHTML of my target div to be the form.

Is this possible?

0 Upvotes
2 Replies 2
miljkovicmisa
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Can I create a hubspot form with a javascript function once needed.

Hi @mswinimer , thank you for writing in the forum.
This is definately possible, you just need to wrap your form in a function that has a arguement and based on that arguement you should run the respective form, it really depends on how your whole application is structured, maybe if you share a piece of code that controls the quiz I could guide you through the rest of the implementation, but this is definately possible, here is an extremly simple example that renders differrent form based on the clicked button:

<button id="f_one" class="js-button">Form One</button>
<button id="f_two" class="js-button">Form Two</button>
<!--[if lte IE 8]>
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js"></script>
<![endif]-->
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
<script>
const allButtons = document.querySelectorAll('.js-button');
allButtons.forEach(function(button){
  button.addEventListener('click', function(){
    const allHolders = document.querySelectorAll('.js-formHolder');
    allHolders.forEach(function(holder){
      holder.innerHTML = '';
    })
    if(this.id == 'f_one'){
      hbspt.forms.create({
        region: "na1",
        portalId: "<YOUR HS PORTAL ID>",
        formId: "<YOUR FORM ID>",
        target: "#formOne"
      });
    } else if(this.id == 'f_two'){
      hbspt.forms.create({
        region: "na1",
        portalId: "<YOUR HS PORTAL ID>",
        formId: "<YOUR FORM ID>",
        target: "#formTwo"
      });
    }
  })
});
/*

*/
</script>

<div id="formOne" class="js-formHolder"></div>
<div id="formTwo" class="js-formHolder"></div>

 

If my answer was helpful please mark it as a solution.

mswinimer
Member | Elite Partner
Member | Elite Partner

Can I create a hubspot form with a javascript function once needed.

As I've continued to look into this, I found some solutions that help accomplish what I was looking to do.
This was helpful: https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml.

0 Upvotes