Categories: CSSScriptWeb Design

Drag-and-drop Form Builder with JSON Outtput – JS FormBuilder

JS FormBuilder is a vanilla JavaScript library that allows you to create an interactive, drag-and-drop form builder.

The library provides a sidebar with draggable components and a canvas area where users can build forms visually.

It generates standardized JSON schemas that store directly in your database.

Features:

  • Lightweight: Uses inline SVG icons and scoped CSS.
  • Sponsored
  • Customizable Components: Configure which form fields appear in the sidebar.
  • JSON Output: Generates a standardized JSON structure.
  • Responsive Design: Works on both desktop and mobile devices.
  • Flexible Layout: Position the component sidebar on the left or right side.

How to Use It

1. Install and import JS FormBuilder with NPM (Recommended for Vite, Webpack, Parcel).

# Install the package from NPM
npm i @heyitsmi/form-builder
// Import the FormBuilder class
import { FormBuilder } from '@heyitsmi/form-builder';

// Import the required stylesheet
import '@heyitsmi/form-builder/form-builder.css';

// Initialize the builder on your target element
const builder = new FormBuilder('#builder-area');

2. You can also load the JavaScript and CSS files directly in the document.

<!-- Load the stylesheet first -->
<link rel="stylesheet" href="/form-builder.css">

<!-- Load the JavaScript library -->
<script src="/form-builder.js"></script>

<script>
  // The FormBuilder class is now available globally
  const builder = new FormBuilder('#builder-area');
</script>

3. Create an empty container element where the form builder will render.

<!-- This div will become the form builder interface -->
<div id="builder-area"></div>

4. Initialize the FormBuilder instance by passing your container selector.

// Create a new FormBuilder instance
// The first parameter is the CSS selector for your container
const builder = new FormBuilder('#builder-area');

5. The library provides a getJson() method that returns the current form structure.

// Attach a click handler to your save button
document.getElementById('save-btn').addEventListener('click', () => {
    // Retrieve the form schema as a JSON object
    const schema = builder.getJson();
    
    // Log the schema to inspect the structure
    console.log(schema);
    
    // Send this schema to your backend API
    fetch('/api/forms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(schema)
    });
});

6. Pass an options object as the second parameter to customize the builder’s behavior.

Sponsored
  • layout (string): Controls the sidebar position. Accepts ‘left’ or ‘right’. Default is ‘left’.
  • components (array): Defines which form components appear in the sidebar. Pass component ID strings or configuration objects. If null, all components are available.
  • icons (object): Overrides default SVG icons. Keys are component IDs, values are SVG markup strings.
// Initialize with custom configuration
const builder = new FormBuilder('#builder-area', {
    // Position the sidebar on the right side
    layout: 'right',
    
    // Show only specific components
    components: [
        'text',
        'textarea',
        // Override the default label for file upload
        { type: 'file', label: 'Upload Document' }
    ],
    
    // Replace default icons with your own SVG markup
    icons: {
        text: '<svg width="24" height="24">...</svg>'
    }
});

Component Types

The library includes eight built-in form components. Use these IDs in the components array.

  • text: Single-line text input field.
  • textarea: Multi-line text input area.
  • number: Numeric input with validation.
  • select: Dropdown selection field.
  • radio: Single-choice radio button group.
  • checkbox: Multiple-choice checkbox group.
  • date: Date picker input field.
  • file: File upload component.

JSON Output Structure

The getJson() method returns an array of field objects. Each field contains configuration properties.

[
  {
    "id": "f_1766565624995",
    "type": "text",
    "label": "Untitled Question",
    "helper": "",
    "required": false,
    "placeholder": ""
  },
  {
    "id": "f_1766565624995",
    "type": "select",
    "label": "Untitled Question",
    "helper": "",
    "required": false,
    "options": [
      "Option 1"
    ]
  },
  {
    "id": "f_1766565628371",
    "type": "select",
    "label": "Untitled Question",
    "helper": "",
    "required": false,
    "options": [
      "Option 1"
    ]
  }
]

FAQs:

Q: Can I validate form fields during the build process?
A: The library focuses on form structure creation. It does not include runtime validation. You can implement validation on the forms you render from the JSON schema.

Q: How do I persist forms across page reloads?
A: Call getJson() to retrieve the schema. Store this JSON in localStorage or send it to your backend API. When the page reloads, pass the saved schema to your form renderer.

Q: How do I handle file upload components in the generated JSON?
A: The file component appears in the JSON schema like other fields. Your form renderer handles the actual file upload logic. The schema stores the field configuration. You implement file upload UI and server communication separately.

The post Drag-and-drop Form Builder with JSON Outtput – JS FormBuilder appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Juniper Networks PTX Vulnerability Enables Full Router Takeover

A major networking vendor has issued an out-of-cycle security bulletin to address a critical vulnerability…

1 minute ago

Microsoft Defender Expands URL Click Alerts to Include Microsoft Teams for Enhanced Security Visibility

Microsoft is strengthening its cybersecurity ecosystem by extending Microsoft Defender for Office 365 (MDO) URL…

2 minutes ago

Bucks County Commissioners Recognize, Honor Black History Through Museum Support

Bucks County Commissioners unanimously approved a proclamation underscoring the importance of Black History month at…

6 minutes ago

‘A Reputable Source for a Quarter Century’ — Metacritic Pulls Resident Evil Requiem Review Over AI Slop Claims, Issues Warning to Other Sites

Metacritic has been forced to remove a suspicious-sounding Resident Evil Requiem review published by a…

11 minutes ago

‘Console Is Where They Want to Be’ — Reports Indicate Sony Is ‘Pulling Away’ From PC for Single-Player PlayStation Games

Sony is reportedly pulling away from PC when it comes to single-player PlayStation games to…

11 minutes ago

How Pokémon’s Accessible Design Has Kept Me Playing Across Three Decades

Today marks the 30th anniversary of the Pokémon franchise. With over 1,000 pocket monsters to…

12 minutes ago

This website uses cookies.