Hubspot form: programmatically set field value via jQuery


#1

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:


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


jQuery Not Working
#2

@damiano.seno.domino Any updates here? I’m working on a subscription page with check/uncheck for email preferences and just struggling with no good result :frowning:


#3

I’m experiencing the same problems since last Friday. Same code just stop to working since then. I opened a ticket on HS but they said the API are normal and no updates lately. Looking forward to hear any updates and solutions.


#4

Still no significant response from HS,they say they are still “investigating”.

I ended up with a slighlty different code that triggers 3 different events (not just the “change” event) using vanilla js instead of jQuery. The conclusion is that there must be a problem with jQuery events and React/Hubspot Forms.

$.fn.notifyHubspot = function() {
  function doEvent( obj, name ) {
    try {
      var event = new Event( name, {target: obj, bubbles: true} );
      return obj ? obj.dispatchEvent(event) : false;
    }
    catch (e) {
      var event = document.createEvent('Event');
      event.initEvent(name, true, true);
      obj.dispatchEvent(event);
    }
  }

  $(this).each(function() {
    doEvent(this, 'change');
    doEvent(this, 'input');
    doEvent(this, 'blur');
  });

  return $(this);
};

$('input[name="firstname"]').val("damiano").notifyHubspot();

Hope this works for you as well.


Embedded form clears prepopulated fields on focus/submit
#5

From my recent experience, the problem is the form is injected after window load by ReactJS.
Furthermore, the hubspot forms have a callback only if injected inside external websites, but not if injected as modules.
We resolved this issue by testing the existance of the form and calling a custom event, to which we attached all manipulations.

Horrible but works:

//Custom form loaded event
if($('#hs_form_target_my_form form').length) {
  $(document).trigger('formLoaded');
} else {
  $('#hs_form_target_my_form').on("DOMNodeInserted",  function(e) {
      if($(e.target).hasClass('hs-form')){
        $(document).trigger('formLoaded');
      }
     
  });
}

#6

Thank you for sharing your experience, but we modify the form after it has been injected via js, so it’s not a timing issue.


#7

I have good news.

The following code:

$('input[name="firstname"]').val("damiano").change();

is working again. HS must have fixed something in their library.

By the way I am waiting for HS official response to my ticket.


#8

That’s good news. Do keep us updated about HS’s official response.

Cheers!


#9

So, now i’m curious about HS response to your ticket


#10

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?


#11

On friday I had to use your event implementation, because it still not works for me.
Infact, the value got overridden by the “old values” from hubspot.
With your “notifyHubspot” react recognizes the first change and stops the overwriting.
Don’t know if it’s clear enough.


#12

@LucaBartoli, We too were having hard time in inserting values dynamically, into input box, now it seems to working.
We were not sure if it was from HS or from our end,whenever we import jquery library from cdn, it gave us error. This time we pasted library on page using hubl. $(‘input[name=“firstname”]’).val(“damiano”).change();
We got it working.


#13

We are using the hubspot provided jquery :frowning:
I think the problem is a little different, because we have no problems in notifying Hubspot normal changes. We have problems in notifying hubspot the first set-up of the fields.
This is necessary because Hubspot automatically selects the old values from the user, but does not notify the changes with any event. We need to reset the form due to this, because Hubspot is slower than our script. So, when we set values before hubspot set its ones, these are overwritten.


#14

I see the bug fixed in one of the instance. But need to confirm if it’s fixed universally for every hubspot instance.

Will post back once I’m assured. :slight_smile:


#15

@LucaBartoli
We got on hubspot forms with custom validation too, I hope this might also be intresting for you :slight_smile:

Hubspot COS, forms with custom validation


#16

@damiano.seno.domino,

I have tried to based on your code. It’s not working myside. My below code is,

hbspt.forms.create({ 
portalId: '3042190',
formId: '2aa8ad7b-81a7-449e-8318-48cf1c26f4b8',
 onFormSubmit: function($form) {   		
	$('input[name="firstname"]').val("Brian").change();   
}  

});

Please let me know, what I missed that.

Thanks,


#17

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:


#18

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.


#19

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!


#20

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