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.
  • 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.

  • 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

Crimson Desert Players Think They’ve Found AI-Generated Art In-Game

Crimson Desert just launched yesterday to a bit of a chaotic and mixed reception from…

14 minutes ago

The FlashForge AD5X Is One of the Best Multi-Color 3D Printers Priced Below $300

One of the better regarded 3D printers with multi-color print capability is now priced well…

14 minutes ago

Today’s Top Deals: Sonic Mini Arcade Cabinet, Budget ASUS TUF Gaming Monitor, and Crimson Desert for PC

Spring is officially here, and that means we’re in for tons of spring sales events…

15 minutes ago

Cathedral Is the First Graphic Novel From Horror Legend John Carpenter

John Carpenter may be about as big a gamer as they come, but never let…

1 hour ago

Google Chrome Update Fixes 26 Security Flaws, Including RCE Vulnerabilities

Google has released a new Chrome stable update that patches 26 security vulnerabilities, including three…

2 hours ago

Critical UNISOC T612 Modem Flaw Enables RCE via Cellular Calls

A critical memory-corruption flaw in UNISOC’s T612 modem family allows remote code execution (RCE) on…

2 hours ago

This website uses cookies.