added script that formats and sends the input to the server

This commit is contained in:
RaffaelW 2024-10-26 11:29:53 +02:00
parent 5d05d30c4d
commit 552cf376a0
2 changed files with 62 additions and 2 deletions

55
data/submit.js Normal file
View file

@ -0,0 +1,55 @@
const form = document.querySelector("form");
function parseValue(input) {
if (input.type === "checkbox") {
return input.checked
? input.dataset.valueChecked
: input.dataset.valueNotChecked;
}
if (input.value === "") {
return null;
}
if (input.type === "number") {
const number = Number(input.value);
return isNaN(number) ? null : number;
}
return input.value;
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const inputFields = document.querySelectorAll(
"form :is(input, select, textarea):not(:disabled)"
);
const data = Array.from(inputFields).reduce((data, input) => {
data[input.name] = parseValue(input);
return data;
}, {});
console.log(data);
putData(data);
});
async function putData(data) {
try {
const res = await fetch("/config", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!res.ok) {
throw new Error(`Response status: ${res.status}`);
}
const json = await res.json();
console.log(json);
} catch (error) {
console.error(error.message);
}
}