APIs & Integrations

domino-dseno
Member | Partner
Member | Partner

Hubspot form: programmatically set field value via jQuery

Hi Community,

I am trying to programmatically set the value of a form field using jQuery, with the following code:

$(‘input[name=“firstname”]’).val(“damiano”).change();

If I paste this code on Chrome console I see that the field changes, but then it gets updated with an empty value if I click on other fields.

The pages I am testing on are:

Donazione per il dispensario medico in Guatemala | MdB

Aiuta anche tu con un piccolo gesto per raccogliere fondi per il dispensario medico e le attività dell'ambulatorio nel Petén, in Guatemala


Code like the above used to work, as it is documented here http://developers.hubspot.com/manipulating-forms-with-jquery

I have opened a ticket on HS, and support is checking if it is really a bug.

Has someone of you experienced this behavior recently?

Thank you very much in advance of your help.

Damiano

34 Replies 34
Rpunkt_digital
Member

Hubspot form: programmatically set field value via jQuery

I'm having exactly the same issue. I can successfully set the initial value of my fields but as soon as I click on and out of one of the fields all pre-set values get deleted again.

 

Does anyone have any news on this issue? I am using the code from the Documentation, although I added "$form" as second argument in the jQuery selector, because otherwise nothing would happen.

 

hbspt.forms.create({ 
    portalId: 'XXXXXX',
    formId: 'aa8b5b4a-62ac-461b-a387-XXXXXXXXXXX',
    onFormReady($form){
    	$('input[name="firstname"]', $form).val('Brian').change();   
   	}
  });
tomcobley
Member

Hubspot form: programmatically set field value via jQuery

I am also having this issue.

 

@Derek_Gervais can you offer any advice?

Albo
Participant

Hubspot form: programmatically set field value via jQuery

@Derek_Gervais I'm also having this problem and would really love some help with it.

 

My use case is leveraging the google maps API to provide autocomplete functionality for the address field. Everything works fine except for that the HS form code keeps clearing the autocompleted values. Tried every variation of jQuery we could think of, but HS keeps clearing the value.

0 Upvotes
Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Hubspot form: programmatically set field value via jQuery

Hey @Albo ,

 

As a general rule, it's better to create a brand new forum post than to post on an older one (>1 year old). Issues from greater than one year ago have usually been resolved, and aren't directly related to new/current issues.

 

That said, I'm happy to dive into whatever is going wrong here. Can you post a link to the page you're referring to so that I can take a closer look?

0 Upvotes
Muhammad_Adnan
Member

Hubspot form: programmatically set field value via jQuery

Someone from this thread can look into this one Cannot read property 'target' of undefined from current.js please

0 Upvotes
Not applicable

Hubspot form: programmatically set field value via jQuery

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.

0 Upvotes
Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Hubspot form: programmatically set field value via jQuery

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.

0 Upvotes
Not applicable

Hubspot form: programmatically set field value via jQuery

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.

Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Hubspot form: programmatically set field value via jQuery

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:

Not applicable

Hubspot form: programmatically set field value via jQuery

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();
}
});

0 Upvotes
Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Hubspot form: programmatically set field value via jQuery

Hi @Payman_Ferdowsali,

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

0 Upvotes
Not applicable

Hubspot form: programmatically set field value via jQuery

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!

0 Upvotes
Not applicable

Hubspot form: programmatically set field value via jQuery

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.

0 Upvotes
Peter_Misura
Member

Hubspot form: programmatically set field value via jQuery

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();

0 Upvotes
jasonbryant
Member

Hubspot form: programmatically set field value via jQuery

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?

WebNikDotLink
Member

Hubspot form: programmatically set field value via jQuery

For anyone who finds this via Google Search - the answer is that form elements need to be manipulated with .change() detailed here: https://developers.hubspot.com/manipulating-forms-with-jquery

This won’t work:
$(‘input[id=“name”]’).val(‘name’);

This will:
$(‘input[id=“name”]’).val(‘name’).change();

0 Upvotes
BorjaInbound
Participant

Hubspot form: programmatically set field value via jQuery

Hello guys,

I’m having some problems with forms and its values, I know it’s not the same thing discussed here but I’d like to know if there’s any way that we can achieve what we need.

The story is the following:

So basically, we’ve built custom private pages for our client’s customers. The thing is that there are many customers groups/segments and we created one private page per group.

So, in order to join these pages, the users must fill out a form inside HubSpot and one of the form fields is called “Security Token”, a single-line text field.

Depending on the group they belong to, the customers will enter a different “Security Token”, with this “token”, we identify the segment where they belong to.

So, for internal purposes, we need to pass the “Security Token” field value into a string parameter in the URL of the page that they’re redirected.

An example:

  1. The user fills out the form (COS Page and HubSpot form), and its token is “TOKEN101”
  2. Form is submitted and it’s redirected to the desination page.
  3. The destination page URL should be “www.example.com/destination-page?token=token101

Is there any way to achieve this? Maybe using Forms API?

Thanks in advance for your time :slight_smile:

0 Upvotes
domino-dseno
Member | Partner
Member | Partner

Hubspot form: programmatically set field value via jQuery

Hi, with this function https://gist.github.com/flexgrip/0ef20e183ca7fe577b5d309620fc44bc you can append the submitted values to the redirect url. Alternatively you can modify it in order to pass only the “token” field.
Hope this helps.
D.

0 Upvotes
BorjaInbound
Participant

Hubspot form: programmatically set field value via jQuery

Thanks for tthe help Damiano! I appreciate it so much :slight_smile:

So, I tried with the following code, but it’s not working at the moment

function appendFormData (form) {

  var redirect = "example.com/example-url";

  var appendFields = function (url, values) {
    var data = {};
    $.each(values, function (i, item) {
      if (item.name !== "token_de_seguridad") {
        data[item.name] = item.value;
      }
    });
    if (url.match(/\?/)) {
      return url + "&" + $.param(data);
    } else {
      return url + "?" + $.param(data);
    }
  };

  var $hsContext = form.find("input[name='token_de_seguridad']");
  var hsContext = JSON.parse($hsContext.val());
  hsContext.redirectUrl = appendFields(redirect, form.serializeArray());
  $hsContext.val(JSON.stringify(hsContext));
}

Also, I added this to the hubspot embed code:

onFormSubmit : function($form, ctx) {
        appendFormData($form);
    }

I modified it in order to pull only the data we need but I think I’m missing out something. With these changes, the form doesn’t redirect, it works because the data is sent, but the redirect doesn’t happen so I think it’s something related to the variables using the parameter “redirectUrl”

Any ideas?

Thanks again for the help

Warm regards!

0 Upvotes
domino-dseno
Member | Partner
Member | Partner

Hubspot form: programmatically set field value via jQuery

Hello,

I got the official response from HS, saying it was a bug introduced by one of their developers.

However the bug has been fixed and I can confirm this. Can you confirm too?

0 Upvotes