How do I add a global JS variable to an embedded form field value?

I have been working on an embedded form that I’d like to update with a value from elsewhere on the page. I have confirmed that the value is set on the document, but it is not passed or accessible from within an embedded form:

var userChoice = "foo";

...

hbspt.forms.create({
...
 onFormReady: function($form) {

 jQuery($form).children().find('input[name=choice]').val(userChoice).change();
 }
});

In this case, the field for “choice” should be set to “foo” but it doesn’t work… is there a way to pass the external value to the form (other than using a query string when the page is first loaded?"

Hi, @dmcknight :waving_hand: Thanks for the interesting question.

I have a few questions of my own to help give our community members more details:

  • have you tried to log userChoice inside the function to ensure it’s not undefined?
  • double-check the browser console for any JavaScript errors that might be preventing your code from running as expected

Another approach is to try using a hidden field in the form that you can update with the userChoice value. This can be a more straightforward approach to passing external values to the form.

Best,

Jaycee

Hi Joyce, I did try console logging `userChoice` inside the `onFormReady` function and it returned as undefined, while console logging it outside of the `hubspot.forms.create` function returns the correct value.

Perhaps this is a more fundamental javascript question, but can I be append the variable to the `hubspot` or `hubspot.forms` object so that it can be accessed from there?