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 handles the rendering, initialization, and runtime behavior of your forms. It takes a template string (typically generated by the Composer class) and renders it into a fully functional, interactive form.

Overview

The Formsmd class is responsible for:
  • Parsing and rendering form templates
  • Managing form state and slide navigation
  • Handling form submissions and validation
  • Managing local storage for form persistence
  • Event handling for user interactions
import { Formsmd } from "formsmd";
import "formsmd/dist/css/formsmd.min.css";

const formsmd = new Formsmd(
  template,
  document.getElementById("container"),
  options
);

formsmd.init();

Constructor

Create a new Formsmd instance:
src/main.js
const formsmd = new Formsmd(template, container, options);

Parameters

template
string
required
The Forms.md template string (from Composer or hand-written)
container
Document | HTMLElement | Element
required
The DOM element where the form will be rendered
options
OptionsType
Configuration options for rendering and behavior

Options

The options object configures runtime behavior:
OptionTypeDefaultDescription
colorScheme"light" | "dark""light"Initial color scheme
isFullPagebooleanfalseWhether to render in full page mode
saveStatebooleantrueSave form data to local storage
sanitizebooleantrueSanitize template content
startSlidenumber0Index of first slide to show
footer"hide" | "show"-Control footer visibility
slideControls"hide" | "show"-Control slide navigation buttons
pageProgress"hide" | "show" | "decorative"-Control progress indicator
formsmdBranding"hide" | "show"-Control Forms.md branding
postDataObject{}Extra data to send with POST requests
postHeadersObject{}Headers for POST requests
getHeadersObject{}Headers for GET requests
errorFieldKeystring"field"Key for field in error objects
errorMessageKeystring"message"Key for message in error objects
prioritizeURLFormDatabooleanfalsePrioritize URL parameters over saved data
sendFilesAsBase64booleanfalseConvert files to base64 for submission
themeLightThemeType-Light theme colors
themeDarkThemeType-Dark theme colors
recaptchaRecaptchaType-Google reCAPTCHA v3 configuration
paddingInlineTopnumber20Top padding for inline forms
paddingInlineBottomnumber20Bottom padding for inline forms
paddingInlineHorizontalnumber0Horizontal padding for inline forms

Initialization

Call init() to render and initialize the form:
src/main.js
const formsmd = new Formsmd(
  composer.template,
  document.getElementById("form-container"),
  {
    saveState: true,
    postHeaders: {
      "Authorization": "Bearer token123"
    }
  }
);

// Initialize the form
formsmd.init();
The init() method must be called after creating the instance to render the form.

State management

Formsmd manages internal state for form data, slide navigation, and field types:
// Access current state
console.log(formsmd.state);

// State structure:
// {
//   data: {},              // Template data blocks
//   formData: {},          // User input values
//   fieldTypes: {},        // Field type mapping
//   settings: {},          // Parsed settings
//   slideData: {           // Slide navigation state
//     currentIndex: 0
//   },
//   bindDivTemplates: {}   // Templates for dynamic content
// }

Resetting state

Reset the form state to defaults:
src/main.js
formsmd.setStateToDefaults();

Local storage

By default, Formsmd saves form data to local storage as users fill out the form. This allows users to return to partially completed forms.

Disabling state persistence

const formsmd = new Formsmd(template, container, {
  saveState: false  // Disable local storage
});

Manual field value saving

src/main.js
formsmd.saveFieldValue("email", "user@example.com");

Clearing saved data

src/main.js
formsmd.removeSavedFormData();
formsmd.removeResponseId();

Form submission

Formsmd handles form submission via POST requests to the configured endpoint.

Basic submission

const composer = new Composer({
  postUrl: "/api/submit"
});

const formsmd = new Formsmd(
  composer.template,
  container,
  {
    postHeaders: {
      "Content-Type": "application/json",
      "Authorization": "Bearer token123"
    },
    postData: {
      source: "website",
      campaign: "summer2024"
    }
  }
);

Handling submission responses

Override the onCompletion method to handle successful submissions:
src/main.js
formsmd.onCompletion = (json) => {
  console.log("Form submitted successfully!", json);
  // Custom success handling
  window.location.href = "/thank-you";
};

formsmd.init();

Custom error handling

Override getSubmissionErrors to handle custom error formats:
src/main.js
formsmd.getSubmissionErrors = (json) => {
  // Default assumes OpenAPI format
  // Customize for your API response structure
  if (json.errors && Array.isArray(json.errors)) {
    return json.errors.map(e => e.message);
  }
  return ["An error occurred"];
};

Event handling

Formsmd automatically adds event listeners for all form interactions:
  • Form field inputs and changes
  • Slide navigation (next/previous)
  • File uploads
  • Code block copy buttons
  • Color scheme toggle
Event listeners are automatically added during initialization. You generally don’t need to manage them manually.

Slide navigation

Formsmd provides methods for programmatic slide control:
const activeSlide = document.querySelector(".fmd-slide.fmd-active-slide");
formsmd.nextSlide(activeSlide);
const activeSlide = document.querySelector(".fmd-slide.fmd-active-slide");
formsmd.prevSlide(activeSlide);

Getting next/previous slides

These methods respect jump conditions and logic:
src/main.js
const { slide, index } = formsmd.getNextSlide();
const { slide, index } = formsmd.getPrevSlide();

Validation

Formsmd handles client-side validation automatically:
src/main.js
const form = document.querySelector("form.fmd-slide");
const isValid = formsmd.formValid(form);

if (!isValid) {
  console.log("Form has validation errors");
}

Field error handling

src/main.js
// Remove errors from a field
const formField = document.querySelector(".fmd-form-field");
formsmd.removeFieldErrors(formField);

// Add custom error
formsmd.addFieldError(
  formField,
  "email-error",
  "Please enter a valid email address"
);

Theming

Configure light and dark themes:
const formsmd = new Formsmd(template, container, {
  colorScheme: "light",
  themeLight: {
    accent: "rgb(30, 55, 153)",
    accentForeground: "rgb(255, 255, 255)",
    backgroundColor: "rgb(255, 255, 255)",
    color: "rgb(0, 0, 0)"
  },
  themeDark: {
    accent: "rgb(138, 180, 248)",
    accentForeground: "rgb(0, 0, 0)",
    backgroundColor: "rgb(20, 20, 20)",
    color: "rgb(240, 240, 240)"
  }
});

Toggle color scheme

Users can toggle between light and dark modes (if enabled in settings):
src/main.js
const event = new MouseEvent("click");
formsmd.toggleColorScheme(event);

Google reCAPTCHA

Integrate Google reCAPTCHA v3 for spam protection:
const formsmd = new Formsmd(template, container, {
  recaptcha: {
    siteKey: "your-recaptcha-site-key",
    action: "submit",
    badgePosition: "bottomright",
    hideBadge: false
  }
});

Complete example

import { Composer, Formsmd } from "formsmd";
import "formsmd/dist/css/formsmd.min.css";

const composer = new Composer({
  id: "contact-form",
  postUrl: "/api/contact",
  title: "Contact Us"
});

composer
  .textInput("name", {
    question: "Your name?",
    required: true
  })
  .emailInput("email", {
    question: "Your email?",
    required: true
  })
  .textInput("message", {
    question: "Your message?",
    multiline: true,
    required: true
  });

const formsmd = new Formsmd(
  composer.template,
  document.getElementById("form-container"),
  {
    saveState: true,
    postHeaders: {
      "Content-Type": "application/json"
    }
  }
);

formsmd.init();

Next steps

Composer

Learn to build templates with Composer

Slides

Create multi-step forms with slides

Conditional logic

Add dynamic behavior to forms