nuzhno-sobrat-formu-registra/script.js

52 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const form = document.getElementById("tb-form");
const msg = document.getElementById("tb-msg");
function showMsg(text, kind) {
msg.textContent = text;
msg.className = "tb-msg " + kind;
}
async function loadCount() {
try {
const r = await fetch("api/registrations?_=" + Date.now());
if (!r.ok) return;
const items = await r.json();
const n = Array.isArray(items) ? items.length : 0;
const el = document.getElementById("tb-count");
if (n > 0) {
el.hidden = false;
el.innerHTML = "Заявило участие: " + n + " чел. из 150 · <a class=\"kt-ai-link\" href=\"participants.html\">смотреть лист участников</a>";
}
} catch (_) {}
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
msg.className = "tb-msg";
const data = {
name: form.name.value.trim(),
dept: form.dept.value.trim(),
email: form.email.value.trim(),
phone: form.phone.value.trim(),
};
if (!data.name || !data.dept || !data.email || !data.phone) {
showMsg("Заполните все поля.", "err");
return;
}
try {
const r = await fetch("api/registrations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!r.ok) throw new Error();
form.reset();
showMsg("Вы зарегистрированы! До встречи 10 октября.", "ok");
loadCount();
} catch (_) {
showMsg("Не удалось отправить заявку. Проверьте соединение и попробуйте ещё раз.", "err");
}
});
loadCount();