I'm been trying to figure this out for hours and I've completely run out of ideas.
I need to change the value of a form with javascript. I'm not using jquery anywhere on the site. When I set the value with javascript, it is visible until I click any other field in the form. The official documentation says to change the value like this:
and makes clear that you have to call the .change(). Since I'm not using jquery, I immediately did a google search to see what jquery is doing and just mimic that with vanilla javascript.
I have a variable 'formFieldEl' which is the input element I have a variable 'value' which represents the value my code:
formFieldEl.value = value formFieldEl.onchange = ()=> formFieldEl.value = value
This does not solve the problem. When I click on any other field, the input value still clears. I know the onchange function is running because if I go back to the input I'm trying to change with javascript and type a new value, when it loses focus the function is called (I tested with a console log).
I get that the form is using react, and react is not recognizing the field value changing with js. I feel like I'm going to need to engineer some way to get to the react component and update it there, but that seems like huge overkill / not sure if even possible.
I can't be the first one to run into this problem.
Friendly reminder, if you set any input as hidden in your form editor, it will get the 'hidden' type. So if you have hidden 'multiple checkboxes', you need to do something like this:
const input = document.querySelector('[name="checkboxes"]');
if (!input) return;
if (input.type === 'hidden') {
// Use an if statement to see if you need to check or uncheck the checkbox
if (checked) {
if (input.value != '') {
input.value = input.value + ';value-for-second-checkbox';
} else {
input.value = 'value-for-first-checkbox';
}
} else {
// Remove the value if the user unchecked the checkbox
input.value = input.value.replace(`;value-for-second-checkbox`, '');
}
input.dispatchEvent(new Event('input', { bubbles: true }));
}
Learn more about HubSpot by following me on LinkedIn or YouTube
✅ Did my answer solve your issue? Help the community by marking it as the solution.