summaryrefslogtreecommitdiff
path: root/frontend/src/components/Forms.ts
blob: ff35065ffb5cd038b53d22b8d07119161f887347 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const API_URL = import.meta.env.VITE_API_URL;

export const setupForm = (form: HTMLFormElement) => {
  if (!form) return;

  const eventId = form.id.replace("rsvp-form-", "");
  const url = `${API_URL}/events/${eventId}/rsvp`;
  const btn = document.getElementById(`submit-${form.id}`);

  async function sendData(form: HTMLFormElement) {
    const formData = new FormData(form);
    const encoded = new URLSearchParams();
    for (let [key, value] of formData.entries()) {
      encoded.append(key, value.toString());
    }
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: encoded,
      });
      if (response.status === 201) {
        form.dataset.submitted = "success";
        if (btn) {
          btn.textContent = "You're going!";
          btn.setAttribute("disabled", "");
        }
      } else if (response.status === 200) {
        form.dataset.submitted = "duplicate";
        if (btn) {
          btn.textContent = "You're already going!";
          btn.setAttribute("disabled", "");
        }
      }
    } catch (e) {
      form.dataset.submitted = "error";
      console.error(e);
    }
  }

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    sendData(form);
  });

  if (btn) {
    const emailInput = form.querySelector("input.rsvp-email");
    if (emailInput) {
      emailInput.addEventListener("input", () => {
        if (btn.textContent !== "Submit RSVP") {
          btn.removeAttribute("disabled");
          btn.textContent = "Submit RSVP";
        }
      });
    }
  }
};

export const setupForms = () => {
  const rsvpForms = document.querySelectorAll("form");
  if (!rsvpForms) return;
  for (let form of rsvpForms) {
    setupForm(form);
  }
};