I am currently working on a project that involves enhancing a tool which enables users to create forms and add various fields to it. Some of these fields are predefined (such as State, Province) and have specific targetable names and classes that are consistent across all forms (e.g. id='region'). However, the format of each field (Input, Textarea, Select, Checkbox, or Radio) can be chosen by the user when adding them to their form. It is crucial for us to be able to update the value of a targeted field (e.g. id="region") without prior knowledge of its input type.
We initially thought that there might be a simple vanilla JavaScript solution available on NPM, but our search did not yield any results. Perhaps we overlooked something?
In the end, we devised the following solution in TypeScript, but we wanted to explore if there are any other existing solutions out there. We would prefer not to reinvent the wheel if someone has already tackled this issue before.
// Set a value to any field. If it's a dropdown, radio, or checkbox, it selects the proper option matching the value
setFieldValue(name: string, value: unknown) {
(document.getElementsByName(name) as NodeListOf<HTMLFormElement>).forEach((field) => {
if ('type' in field) {
switch (field.type) {
case 'select-one':
case 'select-multiple':
for (const option of field.options) {
if (option.value == value) {
option.selected = true;
}
}
break;
case 'checkbox':
case 'radio':
// @TODO: Try to trigger the onChange event
if (field.value == value) {
field.checked = true;
}
break;
case 'textarea':
case 'text':
default:
field.value = value;
}
}
})
return;
}