Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/formsmd/formsmd/llms.txt

Use this file to discover all available pages before exploring further.

The Formsmd class is the main runtime class for rendering and managing Forms.md forms in the browser. It handles initialization, state management, form submission, and user interactions.

Constructor

Create a new Formsmd instance.
const form = new Formsmd(template, container, options);
template
string
required
The Forms.md template string
container
Document | HTMLElement | Element
required
The DOM container where the form will be rendered
options
object
Configuration options

Properties

options
object
The options object passed to the constructor, with defaults applied
container
Element | Document | HTMLElement
The DOM container for the form
state
object
The current form state including:
  • formData: Current form field values
  • data: Data from data blocks
  • settings: Parsed settings from the template
  • slideData: Information about the current slide
  • fieldTypes: Type information for each field
  • bindDivTemplates: Templates for reactive bind divs

Methods

init()

Initialize the form. This renders the template, sets up event listeners, and prepares the form for user interaction.
form.init();
You must call init() after creating a Formsmd instance to render and activate the form.

State Management Methods

setStateToDefaults()

Reset the state to default values.
form.setStateToDefaults();

saveFieldValue()

Manually save a form field value to local storage.
form.saveFieldValue('email', 'user@example.com');
name
string
required
Field name
value
any
required
Field value to save

removeSavedFormData()

Remove all saved form data from local storage.
form.removeSavedFormData();

Color Scheme Methods

setPreferredColorScheme()

Set the preferred color scheme from local storage.
form.setPreferredColorScheme();

toggleColorScheme()

Toggle between light and dark color schemes.
form.toggleColorScheme(event);
e
MouseEvent
required
The click event from the toggle button

nextSlide()

Navigate to the next slide.
const activeSlide = document.querySelector('.fmd-slide-active');
form.nextSlide(activeSlide);
activeSlide
HTMLElement
required
The currently active slide element

prevSlide()

Navigate to the previous slide.
const activeSlide = document.querySelector('.fmd-slide-active');
form.prevSlide(activeSlide);
activeSlide
HTMLElement
required
The currently active slide element

Validation Methods

formValid()

Validate a form and add error messages if necessary.
const form = document.querySelector('form');
const isValid = formsmd.formValid(form);
form
HTMLFormElement
required
The form element to validate
return
boolean
Returns true if the form is valid, false otherwise

removeFieldErrors()

Remove all errors from a form field.
const formField = document.querySelector('.fmd-form-field');
formsmd.removeFieldErrors(formField);
formField
HTMLElement
required
The form field element

addFieldError()

Add an error message to a form field.
formsmd.addFieldError(formField, 'email-error', 'Please enter a valid email');
formField
HTMLElement
required
The form field element
errorId
string
required
Unique ID for the error element
message
string
required
Error message to display

Submission Methods

postFormData()

Submit form data to the configured endpoint.
const result = await form.postFormData(true, false);
if (result.ok) {
  console.log('Submission successful', result.json);
}
postCondition
boolean
required
Whether to check post conditions before submitting
end
boolean
required
Whether this is the final submission (end slide)
return
Promise<object>
Promise that resolves to an object with:
  • ok (boolean): Whether the request succeeded
  • json (object): The response JSON

Data Methods

getRemoteData()

Fetch data from a remote source specified in settings.
const data = await form.getRemoteData();
return
Promise<string>
Promise that resolves to the fetched data as a string

Utility Methods

createRandomId()

Create a random 32-character ID separated by dashes.
const id = form.createRandomId();
// Example: "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
return
string
A randomly generated ID string

getIdPrefix()

Get the prefix for page/form IDs.
const prefix = form.getIdPrefix();
return
string
The ID prefix (empty string if no ID is set)

Event Handler Methods

These methods are automatically attached to form elements during initialization. You can also call them manually if needed.

textFieldOnInput()

Handle input events for text fields.
form.textFieldOnInput(event);

numberFieldOnInput()

Handle input events for number fields.
form.numberFieldOnInput(event);

selectFieldOnInput()

Handle input events for select fields.
form.selectFieldOnInput(event);

choiceFieldOnInput()

Handle input events for choice fields (radio/checkbox).
form.choiceFieldOnInput(event);

datetimeFieldOnInput()

Handle input events for datetime fields.
form.datetimeFieldOnInput(event);

fileFieldOnInput()

Handle input events for file upload fields.
form.fileFieldOnInput(event);

Overridable Methods

These methods can be overridden to customize behavior.

getSubmissionErrors()

Extract error messages from a JSON response. Override this to support different error formats.
form.getSubmissionErrors = function(json) {
  // Custom error extraction logic
  return json.errors.map(e => e.message);
};
json
object
required
The JSON response from form submission
return
string[]
Array of error message strings
By default, this method assumes OpenAPI error format. Override it to support your API’s error format.

onCompletion()

Called when the user reaches the end slide. Override this to execute custom logic on form completion.
form.onCompletion = function(json) {
  console.log('Form completed!', json);
  // Custom completion logic
};
json
object
required
The JSON response from the final form submission

Example

import { Formsmd } from '@formsmd/runtime';

const template = `
#! title = Customer Survey

-> start

# Welcome

Thank you for your time.

---

name* = TextInput(
  |question = What is your name?
)

email* = EmailInput(
  |question = What is your email?
)

---

satisfaction* = RatingInput(
  |question = How satisfied are you?
  |outOf = 5
)

---

-> end

# Thank you!

We appreciate your feedback.
`;

const container = document.getElementById('form-container');

const form = new Formsmd(template, container, {
  colorScheme: 'light',
  saveState: true,
  postUrl: 'https://api.example.com/responses',
  themeLight: {
    accent: 'rgb(59, 130, 246)',
    accentForeground: 'rgb(255, 255, 255)'
  }
});

// Override onCompletion to handle success
form.onCompletion = function(json) {
  console.log('Form submitted successfully!', json);
  window.location.href = '/thank-you';
};

// Initialize the form
form.init();

Browser Events

The Formsmd class automatically handles the following browser events:
  • Input events: Updates state and triggers validation
  • Submit events: Validates and submits form data
  • Click events: Handles navigation, color scheme toggle, and file resets
  • Focus events: Manages autofocus behavior

Local Storage

When saveState is enabled (default), the following data is stored in local storage:
  • Form data: Current values of all form fields
  • Response ID: Unique identifier for the current form session
  • Color scheme: User’s preferred color scheme
Data is automatically cleared when the user completes the form.