SDK component for sourcing HTML form information.
The Form Wrapper is an important helper function that extracts data from a HTML form, and passes it as a JSON object to a specified function.
Method
Accepts a string and a function as arguments.
- formId – The ID of the HTML form.
- func – The name of the function you want to pass the form data to.
//Helper method to extract a JS object from a DOM form
function wrapForm(formId, func) {
let form = document.getElementById(formId);
form.onsubmit = function (event) {
const formData = {};
event.preventDefault();
for (let i = 0; i < form.elements.length; ++i) {
if (form.elements[i].name) {
let root = formData;
const path = form.elements[i].name.split('-');
const value = form.elements[i].value;
path.slice(undefined, -1).forEach(function (key) {
if (root[key] === undefined) {
root[key] = {};
}
root = root[key];
});
//Assign value to leaf
root[path[path.length - 1]] = value;
}
}
//Call func with unpacked formData
func(formData);
};
}