Getting started
You need three things: a form with an id, a submit button, and a URL that accepts the form data. formsub runs in the browser only.
1. Load the library
Pick one way to include it.
Script tag (IIFE)
After npm run build, host dist/formsub.min.js and load it:
html
<script src="/path/to/formsub.min.js"></script>formsub is then available on window.
During development you can load the non-minified formsub.js so stack traces stay readable.
npm (ES module)
bash
npm install formsubhtml
<script type="module">
import formsub from 'formsub';
formsub.newForm({ /* options */ });
</script>If the package is published, a CDN works the same as a script tag:
html
<script src="https://cdn.jsdelivr.net/npm/formsub/dist/formsub.min.js"></script>2. Write a form
Every field you want to send needs a name. The form id must match formId exactly (not a CSS selector).
html
<form id="contact-form">
<label>
Name
<input name="name" type="text" required />
</label>
<label>
Email
<input name="email" type="email" required />
</label>
<p id="loading" class="hidden">Sending…</p>
<button type="submit" id="submit-button">Send</button>
</form>3. Bind it
js
formsub.newForm({
formId: 'contact-form',
submitButton: '#submit-button',
ajaxUrl: '/api/contact',
method: 'POST',
indicator: '#loading',
});On submit, formsub:
- Stops the browser from navigating
- Checks
requiredand email fields - Sends
FormDatatoajaxUrl - Shows inline errors or a success state from your JSON
If formId, submitButton, or ajaxUrl is missing, or the nodes are not in the DOM, newForm logs a console.error and does not bind anything.
Required setup
| You provide | Why |
|---|---|
Form id | Must match formId exactly |
| Submit button selector | submitButton is a CSS selector (#submit-button) |
| Endpoint | ajaxUrl is passed to fetch |
Field name attributes | Unnamed fields are not sent and cannot show field errors |
Handle the response yourself
Leave callback unset to use the built-in UI (inline errors, optional SweetAlert2, form reset on success). Pass a function if you want to own the UI:
js
formsub.newForm({
formId: 'contact-form',
submitButton: '#submit-button',
ajaxUrl: '/api/contact',
callback: (response) => {
if (response.status === 'success') {
alert(response.message);
}
},
});Native form attributes
action and method on the <form> tag are ignored. Use ajaxUrl and the method option instead.
Next
- Configuration — every option
- Forms & markup — HTML structure and error styling
- Server responses — JSON your API should return
- Playground — live demo in this repo