# Formtress.js - A JavaScript library for handling your Formtress forms

[![npm version](https://badge.fury.io/js/formtress-js.svg)](https://badge.fury.io/js/formtress-js)

`formtress.js` is a tiny library that submits your forms using JavaScript, and handles loading states, validation, and error messages.

## Features

- **Lightweight**: Under 1KB minified and gzipped.
- **Easy to use**: Just add a few attributes to your form and you're good to go.
- **Built-in validation**: Automatically validates your forms based on the forms you created in Formtress.
- **Error handling**: Automatically handles errors and displays them to the user.
- **Platform specific**: Built-in integrations for Webflow, with a core module for any project.

## Installation

### CDN (Webflow)

Add the following script to your Webflow project settings before the closing `</body>` tag (change `latest` to the version you want to use):

```html
<script src="https://cdn.jsdelivr.net/npm/formtress-js@latest/dist/js/webflow.js"></script>
```

> Note: It's recommended to pin to a specific version in production for stability. Check the version badge above for the current release.

### npm

```bash
npm install formtress-js
```

## Usage

### Webflow

1. Copy the form ID from your [Formtress](https://app.formtress.com) account.
2. In Webflow's form settings, set the form **Action** to your Formtress endpoint:
   ```
   https://app.formtress.com/api/f/{your-form-id}
   ```
3. That's it! The script enhances the form progressively:
   - **Without JavaScript**: the form submits natively to Formtress, keeping it functional for all users.
   - **With JavaScript**: the submission is intercepted and handled client-side, showing loading states and success/fail panels without a page reload — just like Webflow's native form behaviour.

If you changed the default structure of the error message element, add a `data-ft-error` attribute to the text element that should display the error message.

> **Note (v0.2.0 breaking change):** The previous `data-ft="your-form-id"` attribute is no longer used. Set the form `action` as described above instead.

### Core (any project)

Set the form `action` to your Formtress endpoint so it works without JavaScript:

```html
<form id="my-form" action="https://app.formtress.com/api/f/your-form-id" method="POST">
  <!-- your fields -->
</form>
```

Then progressively enhance it with JavaScript:

```js
import { submitForm } from 'formtress-js'

const form = document.querySelector('#my-form')
form.addEventListener('submit', async (e) => {
  e.preventDefault()
  const result = await submitForm({
    url: form.action,
    data: new FormData(form),
  })
  if (result.ok) {
    // show success state
  } else {
    // show error state: result.message, result.status
  }
})
```