Categories: CSSScriptWeb Design

Chatbot-like Conversational Form Builder in Vanilla JavaScript – FormBotJS

FormBotJS is a lightweight JavaScript library that transforms standard HTML forms into an interactive, chatbot-style conversation UI.

It guides your users through form completion using a chat-style question-and-answer flow that feels natural and engaging. Ideal for multi-step forms where you want to reduce user fatigue and increase completion rates.

Features:

  • Multiple Input Types: Handles text, email, number, date, file uploads, radio buttons, select dropdowns, and multiselect fields through a unified interface.
  • Built-in Validation: Uses HTML5 validation attributes like required, minlength, maxlength, and pattern for form control.
  • Flexible Submission: Supports both AJAX POST to server endpoints and callback-only modes for custom handling.
  • Theme Customization: Includes light and dark mode toggle with customizable primary color through CSS variables.
  • Local Storage Integration: Optional answer persistence across sessions for form recovery.
  • Progress Tracking: Visual progress indicator showing completion status through the conversation flow.
  • File Preview: Displays uploaded images directly in the chat interface with configurable size limits.

Use Cases

  • Onboarding Flows: Guide new users through account setup with a friendly, conversational approach that feels more like assistance than interrogation.
  • Survey Forms: Break long surveys into manageable steps to reduce abandonment rates and improve data quality.
  • Lead Generation: Create engaging contact forms that feel more like a conversation than a formal submission process.
  • Customer Feedback: Collect detailed feedback through a guided conversation that encourages more thoughtful responses.

How To Use It:

1. Load the FormBotJS CSS and JavaScript files in your HTML document:

<link rel="stylesheet" href="src/formbot.min.css">
<script src="src/formbot.min.js"></script>

2. Create a container element where the chat form will render:

<div id="chat-form"></div>

3. Initialize FormBot with a configuration object containing your container ID and questions array:

new FormBot({
  chat_containerId: "chat-form",
  chat_form_title: "Contact Us",
  questions: [
    {
      label: "What's your name?",
      name: "name",
      type: "text",
      attrs: { required: true, placeholder: "John Doe" }
    },
    {
      label: "What's your email address?",
      name: "email",
      type: "email",
      attrs: { required: true, placeholder: "john@example.com" }
    },
    {
      label: "Thanks! We'll be in touch soon.",
      name: "end_message",
      type: "message"
    }
  ],
  onComplete: (answers) => {
    console.log("Form submitted:", answers);
  }
});

4. Each question object defines a step in the conversational form:

Property Type Description
label String The question text displayed to the user
name String Field name used in form submission and answers object
type String Input type: text, email, number, date, file, textarea, select, multiselect, radio, checkbox, hidden, message
options Array Available choices for select, multiselect, radio, and checkbox types
attrs Object HTML attributes applied to the input element (required, placeholder, min, max, accept, etc.)

5. Available input types:

  • Text-based inputs: text, email, number, textarea, date
  • Selection inputs: select (single choice), multiselect (multiple choices), radio, checkbox
  • File input: file (supports accept attribute and data-maxsize for validation)
  • Special types: message (display-only bot message), hidden (included in submission but not displayed)

6. Place validation rules inside the attrs object. Validation attributes include required, minlength, maxlength, pattern, min, max, step, accept (for files), and data-maxsize (file size in MB).

{
  label: "What's your phone number?",
  name: "phone",
  type: "text",
  attrs: {
    required: true,
    pattern: "[0-9]{3}-[0-9]{3}-[0-9]{4}",
    placeholder: "123-456-7890",
    title: "Format: 123-456-7890"
  }
}

7. All configuration options:

Option Description
chat_containerId (Required) The ID of the HTML element where the chat form will be rendered.
post_url The server endpoint URL where the form data will be sent via a POST request.
chat_form_title The title displayed at the top of the chat window. Default is ‘Chat Assistant’.
color1 Sets the primary theme color for the chat interface.
mode Set to "submit" to POST data to post_url or "return" to only execute the onComplete callback.
extraData An object containing extra key-value pairs to append to the FormData (e.g., a CSRF token).
showProgress A boolean to show or hide the progress bar at the bottom.
saveToLocalStorage A boolean to save the user’s progress in local storage.
questions (Required) An array of question objects that define the conversation flow.
onComplete A callback function that runs when the form is completed. It receives answers and formData.
FormBot.init({
  chat_containerId: "chat-form-container", // required
  post_url: "/api/submit",                  // server endpoint (used when mode === "submit")
  color1: "#28a745",                        // primary color (updates CSS var)
  mode: "submit",                           // "submit" or "return"
  extraData: { _token: "CSRF_TOKEN_HERE" }, // appended to FormData
  showProgress: true,
  saveToLocalStorage: true,
  questions,                                // pass the questions array
  onComplete: (answers, formData) => {
    // answers = [{name, label, value, file?}, ...]
    // formData = FormData instance (useful if you want to send it yourself)
    console.log("collected:", answers);
  }
});

8. Advanced Example with Multiple Features:

new FormBot({
  chat_containerId: "advanced-form",
  chat_form_title: "Job Application",
  post_url: "/api/applications",
  color1: "#2563eb",
  mode: "submit",
  showProgress: true,
  saveToLocalStorage: true,
  extraData: { 
    application_type: "developer",
    _token: "csrf_token_here" 
  },
  questions: [
    {
      label: "Let's start with your full name:",
      name: "name",
      type: "text",
      attrs: { required: true, minlength: 2 }
    },
    {
      label: "What position interests you?",
      name: "position",
      type: "select",
      options: ["Frontend Developer", "Backend Developer", "Full Stack Developer"],
      attrs: { required: true }
    },
    {
      label: "How many years of experience do you have?",
      name: "experience",
      type: "number",
      attrs: { required: true, min: 0, max: 50 }
    },
    {
      label: "Upload your resume (PDF, max 5MB):",
      name: "resume",
      type: "file",
      attrs: { 
        required: true, 
        accept: ".pdf",
        "data-maxsize": "5"
      }
    },
    {
      label: "Application received! We'll review and get back to you.",
      name: "confirmation",
      type: "message"
    }
  ],
  onComplete: (answers, formData) => {
    console.log("Application data:", answers);
    // Custom handling if mode is "return"
  }
});

FAQs

Q: Can I conditionally show or hide questions based on previous answers?
A: FormBotJS processes questions sequentially from the questions array without built-in conditional logic. You can implement conditional flows by dynamically generating the questions array before initialization based on your logic, or by using the onComplete callback to determine which form instance to show next.
Q: How do I handle form submission errors from my server?

A: When using mode “submit”, FormBotJS sends data via AJAX but does not expose error handling hooks directly. Switch to mode “return” and handle submission yourself in the onComplete callback where you have full control over error handling, retry logic, and user feedback. You can access the FormData object as the second parameter and use fetch or XMLHttpRequest with proper error handling.

Q: How can I validate answers with custom logic beyond HTML5 validation?
A: For complex validation like checking email availability or validating against external data, use mode “return” and validate the answers array in your onComplete callback. You can then show custom error messages or reinitialize the form with appropriate feedback. The library currently does not provide hooks for inline custom validation during the conversation flow.

The post Chatbot-like Conversational Form Builder in Vanilla JavaScript – FormBotJS appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Universal Pixels leverages Panasonic AI Powered software and Cameras to showcase Oasis reunion tour

Panasonic has revealed how it helped to power the displays during the Oasis’ global Live…

37 minutes ago

Precisely Unveils Governed AI for Regulated Communications

Precisely has launched its latest EngageOne RapidCX update. Its focus is on bringing governed AI…

37 minutes ago

Building a strategy for the effective use of AI

Start with the ‘Why?’ When identifying the use case for AI, it is essential that…

37 minutes ago

Deltek launches 7th Annual Clarity Report

Deltek has published its seventh annual global Clarity report, a comprehensive industry study of the…

38 minutes ago

Infor and AWS launch a range of industry specific AI agents

Infor and Amazon Web Services (AWS) have announced the development of advanced industry-specific AI agents…

38 minutes ago

Coyote vs. Acme Debut Trailer

Here we go, folks: the Coyote vs. Acme trailer has officially exploded onto the scene.…

40 minutes ago

This website uses cookies.