in/static/form.js
2022-08-04 05:41:51 +02:00

103 lines
2.9 KiB
JavaScript

let items = {};
const id = new URLSearchParams(window.location.search).get('id');
document.onreadystatechange = function() {
if (document.readyState === 'interactive') {
fetch('/api/items').then(r => r.json()).then((data) => {
items = data;
fillForm();
});
}
}
function fillForm() {
const item = items[id];
const is_in = document.getElementById('is_in');
for (const [_, item] of Object.entries(items)) {
const option = document.createElement('option');
option.value = item.id;
option.textContent = `${item.id} ${item.name && `(${item.name})` || ''}`
is_in.appendChild(option);
};
document.getElementById('id').placeholder = '';
if (id && item) {
document.getElementById('id').value = item.id;
document.getElementById('is_in').value = item.is_in;
document.getElementById('coords_bl').value = item.coords_bl;
document.getElementById('coords_tr').value = item.coords_tr;
document.getElementById('type').value = item.type;
document.getElementById('name').value = item.name;
document.getElementById('content').value = item.content;
document.getElementById('note').value = item.note;
document.getElementById('hidden').checked = item.hidden;
}
const saveBtn = document.getElementById('save');
const delBtn = document.getElementById('delete');
saveBtn.onclick = function(e) {
e.preventDefault();
save();
};
delBtn.onclick = function(e) {
e.preventDefault();
del();
}
}
function save() {
item = {
id: document.getElementById('id').value || null,
is_in: document.getElementById('is_in').value || null,
coords_bl: document.getElementById('coords_bl').value || null,
coords_tr: document.getElementById('coords_tr').value || null,
type: document.getElementById('type').value || null,
name: document.getElementById('name').value || null,
content: document.getElementById('content').value || null,
note: document.getElementById('note').value || null,
hidden: document.getElementById('hidden').checked,
}
if (items[item.id]) {
if (!id || (id && id != item.id)) {
alert(`ID ${item.id} exists. Please chose a different ID or edit the existing ${item.id} item!`);
return;
}
}
const original_id = id || item.id;
fetch(`/api/items/${original_id}`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(item),
})
.then(r => {
if (r.ok) {
window.location.href = '../';
} else {
r.text().then(t => alert(`Error:\n${t}`));
}
}).catch(error => {
alert(`Error:\n${error}`);
});
}
function del() {
if (id && confirm('Are you sure?')) {
fetch(`/api/items/${id}`, {method: 'DELETE'}).then(r => {
if (r.ok) {
window.location.href = '../';
} else {
r.text().then(t => alert(`Error:\n${t}`));
}
}).catch(error => {
alert(`Error:\n${error}`);
});
}
}