JSFiddle - React, Tailwind, and code Playground
HTML
<form>
<input type="text" name="name">
<label>
<input type="checkbox" name="tags" value="foo">
foo
</label>
<label>
<input type="checkbox" name="tags" value="bar">
bar
</label>
<label>
<input type="checkbox" name="tags" value="ding">
ding
</label>
<label>
<input type="checkbox" name="tags" value="dong">
dong
</label>
</form>
JavaScript
const form = document.querySelector("form");
updateForm(form, {
name: "John Doe",
tags: ["ding", "bar"],
});
/**
* See https://findk.it/update-form
*
* @param {HTMLFormElement} form
* @param {{ [key: string]: string | string[] }} data
*/
function updateForm(form, data) {
for (const [key, values] of Object.entries(data)) {
const item = form.elements.namedItem(key);
const arrayValues = Array.isArray(values) ? values : [values];
for (const value of arrayValues) {
const list =
item instanceof RadioNodeList ? Array.from(item) : [item];
for (const el of list) {
if (el instanceof HTMLSelectElement) {
for (const option of el.options) {
if (option.value === value) {
option.selected = true;
continue;
}
}
} else if (el instanceof HTMLInputElement) {
if (el.type === "checkbox" || el.type === "radio") {
if (el.value === value) {
el.checked = true;
continue;
}
} else {
el.value = value;
}
}
}
}
}
}