#How to handle form when used in top level frontmatter?

3 messages · Page 1 of 1 (latest)

covert locust
#

I have a form enclosed within a dialog element. currently when i click submit, it closes the dialog. is there a way to prevent this default behaviour?

since i want to peform the actions that are available at top level frontmatter, i cant use e.preventDefault()

this is my code

---
const { buttonText } = Astro.props;
import { z } from "astro:content";
import { createForm, validateForm } from "simple:form";

export const ProductEnquiryForm = createForm({
  name: z.string(),
  email: z.string().email(),
  phone: z.string(),
});

if (Astro.request.method === "POST") {
  // stop closing the dialog when submit button is clicked
  // and instead show a success message
  // user can close the form by clicking close button
  // validate and call api

}
---

<button
  onclick={`document.getElementById('dialog').showModal()`}
>
  {buttonText}
</button>
<dialog
  id="dialog" 
>
  <form method="POST" class="grid gap-4">
    <div>
      <div>
        <label for="name">Name *</label
        >
        <input type="text" id="name" name="name" required />
      </div>

      <div>
        <label for="email" >Email *</label>
        <input type="email" id="email" name="email" required />
      </div>

      <div>
        <label for="phone">Phone *</label
        >
        <input
          type="tel"
          id="phone"
          name="phone"
          required
          />
      </div>
    </div>
  </form>

  <hr class="my-4" />
  <div class="grid grid-flow-col gap-4">
    <button type="reset">Close</button>
    <button type="submit">Submit</button>
  </div>
</dialog>

<script is:inline>
// js to select buttons and handle form reset
</script>

brittle swift
#

Change your submit button to type="button" and handle the click yourself.

covert locust
#

but then i would need to handle it client side right? i want to handle form submission logic server side.