I'm trying to set the values for some form fields of a hubspot form with javascript. But the values gets deleted after validation (or in this case after input/change event). I remember that this used to work (and it's also the solutions in a lot of other posts). Has anyone an idea what could be the problem? Or am I doing something wrong?
window.addEventListener('message', event => {
const formId = "MY_FORM_ID";
if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady' && event.data.id === formId) {
const form = document.querySelector(`[data-form-id="${event.data.id}"]`);
// doesn't work - triggers validation without setting the value
const emailfield = form.elements.email;
emailfield.value = "myemail@address.com";
emailfield.dispatchEvent(new Event('input', { 'bubbles': true }));
const companyfield = form.elements.company;
companyfield.value = "MyCompanyName";
companyfield.dispatchEvent(new Event('input', { 'bubbles': true }));
const adressfield = form.elements.address;
adressfield.value = "MyAddress";
adressfield.dispatchEvent(new Event('input', { 'bubbles': true }));
// doesn't work the jquery way either
//$(companyfield).val("MyCompanyName").change();
}
});
I haven't been able to get the global event listener to work for changing field inputs for a few months now. Not sure if HubSpot made some change that rendered field changing impossible in the event listener or what, but even some of our old forms that we hadn't touched for over a year just straight up suddenly stopped working. Switched to using the form embed code and putting JavaScript directly in the callback. Bit annoying, but it at least works.
hbspt.forms.create({
portalId: '',
formId: '',
onFormReady: function($form) {
// YOUR SCRIPT HERE
}
});
If this answer solved your question, please mark it as the solution.
I haven't been able to get the global event listener to work for changing field inputs for a few months now. Not sure if HubSpot made some change that rendered field changing impossible in the event listener or what, but even some of our old forms that we hadn't touched for over a year just straight up suddenly stopped working. Switched to using the form embed code and putting JavaScript directly in the callback. Bit annoying, but it at least works.
hbspt.forms.create({
portalId: '',
formId: '',
onFormReady: function($form) {
// YOUR SCRIPT HERE
}
});
If this answer solved your question, please mark it as the solution.
hey @piersg, I tried that as well unfortunately it doesn't trigger the validation at all (and after the form submission it again clears the input). It seems that the react form fields only listen to the input event. I also tried it with jquery as it was mentioned in other posts but without success: