Skip to content

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 formsub
html
<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:

  1. Stops the browser from navigating
  2. Checks required and email fields
  3. Sends FormData to ajaxUrl
  4. 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 provideWhy
Form idMust match formId exactly
Submit button selectorsubmitButton is a CSS selector (#submit-button)
EndpointajaxUrl is passed to fetch
Field name attributesUnnamed 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

Released under the MIT License.