npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

form-populator

v1.2.5

Published

Lightweight vanilla JS utility to instantly sync API data (or any object) into forms and DOM elements. One call populates inputs, checkboxes, radios, selects (native/TomSelect/Selectize/Chosen/AutoNumeric), content, lists, and attributes. Extract values b

Downloads

223

Readme

FormPopulator

MIT License Zero Dependencies

Lightweight vanilla JS utility for populating and extracting values from HTML forms and DOM elements. It uses object keys to match elements by name or id attributes, handling all form types and optionally the enhanced select libraries (tomSelect, Selectizer, Chosen) or autoNumeric.org automatically.

Features

  • One-call population — Pass a container and data object, done
  • Bidirectionalpopulate() to fill, getValues() to extract
  • All form elements — text, email, tel, number, date, checkbox, radio, select, textarea, file (readonly)
  • Enhanced selects — Optional: TomSelect, Selectize, Chosen auto-detected and handled
  • AutoNumeric — Optional: Formatted currency/number inputs populated and extracted correctly
  • DOM elements — span, div, p, h1-h6, ul, ol (including nested lists), img, video, audio, iframe, a
  • Attributes — Set any attribute (including data-*) alongside values
  • XSS-safe — HTML sanitized by default (textContent), opt-in for innerHTML
  • Lookup priority — Finds elements by name first, falls back to id
  • Loose equality — Matches 1 to "1" (real form behavior)
  • Zero dependencies — Pure vanilla JavaScript, works everywhere

Installation

Manual

Download dist/form-populator.min.js and include it:

<script src="path/to/form-populator.min.js"></script>

Quick Start

<form id="userForm">
  <input name="firstName" type="text">
  <input name="email" type="email">
  <input name="newsletter" type="checkbox" value="yes">
  <select name="role">
    <option value="">Select...</option>
    <option value="admin">Admin</option>
    <option value="user">User</option>
  </select>
</form>

<script>
const form = document.getElementById('userForm');

// Populate from API response
FormPopulator.populate(form, {
  firstName: 'John',
  email: '[email protected]',
  newsletter: 'yes',
  role: 'admin'
});

// Extract values back
const values = FormPopulator.getValues(form, ['firstName', 'email', 'newsletter', 'role']);
// → { firstName: 'John', email: '[email protected]', newsletter: 'yes', role: 'admin' }
</script>

API Reference

FormPopulator.populate(container, data, attributes?, sanitizeHtml?)

Populates elements inside container with values from data.

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | container | HTMLElement | — | Parent element containing target elements | | data | Object | — | Key-value pairs where key matches element name or id | | attributes | Object | {} | Optional attributes to set per key | | sanitizeHtml | boolean | true | Use textContent (safe) or innerHTML (raw) |

FormPopulator.getValues(container, keys)

Extracts values from elements inside container.

| Parameter | Type | Description | |-----------|------|-------------| | container | HTMLElement | Parent element containing target elements | | keys | string[] | Array of element names/ids to extract |

Returns: Object with key-value pairs. Unchecked checkboxes and missing elements are omitted.

Usage Examples

Checkboxes

// Single checkbox — pass the value to check it
FormPopulator.populate(container, { acceptTerms: 'yes' });

// Checkbox group — pass array of values
FormPopulator.populate(container, { 
  interests: ['sports', 'music', 'tech']
});

// Clear all checkboxes — pass null, undefined, or empty array
FormPopulator.populate(container, { interests: null });

Radio Buttons

// Select by value
FormPopulator.populate(container, { paymentMethod: 'credit_card' });

// Numeric values work (loose equality)
FormPopulator.populate(container, { rating: 5 }); // matches value="5"

Select Elements

// Single select
FormPopulator.populate(container, { country: 'mx' });

// Multiple select — pass array
FormPopulator.populate(container, { 
  languages: ['en', 'es', 'fr']
});

// Clear select — pass null or empty string
FormPopulator.populate(container, { country: null });

TomSelect / Selectize / Chosen

No extra configuration needed — FormPopulator auto-detects initialized instances:

// Works the same as native selects
FormPopulator.populate(container, { 
  tags: ['javascript', 'php', 'mysql']
});

AutoNumeric Inputs

Formatted currency/number inputs are handled automatically:

// Set value (AutoNumeric formats it)
FormPopulator.populate(container, { price: 1234.56 });
// Input displays: $1,234.56

// Extract returns raw numeric string
const values = FormPopulator.getValues(container, ['price']);
// → { price: '1234.56' }

Lists (ul/ol)

// Simple list
FormPopulator.populate(container, { 
  ingredients: ['Flour', 'Sugar', 'Eggs']
});

// Nested list
FormPopulator.populate(container, { 
  menu: ['Appetizers', ['Salad', 'Soup'], 'Main Course']
});

Media Elements

FormPopulator.populate(container, {
  profileImage: '/images/user.jpg',      // <img> → sets src
  introVideo: '/videos/intro.mp4',       // <video> → sets src
  documentLink: '/docs/manual.pdf'       // <a> → sets href
});

Setting Attributes

FormPopulator.populate(container, 
  { userId: '12345' },
  { 
    userId: { 
      'data-validated': 'true',
      'class': 'highlight',
      'disabled': null  // null removes attribute
    }
  }
);

Raw HTML (opt-in)

// Default: sanitized (safe)
FormPopulator.populate(container, { message: '<b>Bold</b>' });
// → displays literal "<b>Bold</b>"

// Opt-in: raw HTML
FormPopulator.populate(container, { message: '<b>Bold</b>' }, {}, false);
// → displays Bold

Extraction Examples

// Single values
const { email } = FormPopulator.getValues(form, ['email']);

// Multiple checkbox group returns array
const { permissions } = FormPopulator.getValues(form, ['permissions']);
// → ['read', 'write'] if multiple checked
// → 'read' if single checked
// → (key omitted if none checked)

// Radio returns checked value or empty string
const { status } = FormPopulator.getValues(form, ['status']);
// → 'active' or ''

// Multiple select returns array
const { categories } = FormPopulator.getValues(form, ['categories']);
// → ['cat1', 'cat2']

Element Lookup Priority

FormPopulator finds elements by name first, then falls back to id:

<!-- Found by name -->
<input name="email" id="emailField">

<!-- Found by id (no name match) -->
<div id="statusMessage">...</div>

When both exist with same key, name wins:

<div id="userType">Display div</div>
<input type="radio" name="userType" value="admin">
<input type="radio" name="userType" value="user">

<!-- populate({ userType: 'admin' }) → selects radio, ignores div -->

Browser Support

Works in all modern browsers (Chrome, Firefox, Safari, Edge). Uses CSS.escape() for safe selectors.

Module Usage

// ES Modules
import FormPopulator from 'form-populator';

// CommonJS
const FormPopulator = require('form-populator');

AI Assistant Integration

This library is optimized for use with AI coding assistants. We provide specific context files to help LLMs understand how to integrate FormPopulator correctly:

  • CLAUDE.md: A streamlined guide tailored for Anthropic's Claude.
  • GEMINI.md: Integration manual and troubleshooting checklist for Google Gemini.

Use these files to prime your AI session for better code generation, or as the basis for your own custom integration guide.

License

MIT © Raúl José Santos