Populate a form or an element's child elements using a JSON object.
I don’t like mixing HTML and PHP when I build my forms. Instead I like to keep my HTML completely clean, then if a form needs to be pre-filled (for example retrieving a bunch of database results), get JavaScript to fill it in for me after the page has loaded.

This plugin supports full PHP naming and deep data structures, as well as checkbox arrays, other non-standard UI controls, and even standard HTML elements such as labels or divs.
The plugin can be used as part of your AJAX toolkit, or for separating server-side code from HTML by populating a form after the page has loaded eg:
$('form').populate({text:'text', radio:1})
and not inline as the page is processed, such as:
<input type="text" name="text" id="text" value="<?php echo $text; ?>" />
<input type="radio" name="radio" id="radio-1" checked="<?php echo $val == 1; ?>" />
<input type="radio" name="radio" id="radio-2" checked="<?php echo $val == 2; ?>" />
You can also populate non-form controls such as <div>s, by specifiying the id and an identifying attribute (defaults to id):
$('div').populate({'text-1':'text', 'text-2':'More text'})
This can be useful when you want to show the results of a database call, but don’t want the text to be editable.
Instructions and demos
View the jQuery Populate demo for a view a full set of instructions and a working demo, with examples of populating:
- a simple form, using string variable types for textfields, radiobuttons, dropdowns and checkboxes
- a complex form, using array variable types for checkbox arrays and multi-list boxes
- a hierarchical form, using hierarchical JSON data
Update 29th November 2009
Thanks to everyone who spotted bugs and contributed their comments. The following features are added / bugs are now squished:
- Now populates standard HTML elements within forms
- Is now case-sensitive for element value comparisons (keith, 5030SDEC, Mark Croxton)
- Now skips function references and undefined elements (Henning, Found-a-Bug)
- Fixed debug trace for missing elements (Found-a-Bug)
Download
JavaScript
PHP
Demo files
Fixed debug trace for missing elements (Found-a-Bug)
Now skips function references and undefined elements (Henning, Found-a-Bug)
Now populates standard HTML elements
Is now case-insensitive for element value comparisons (keith, 5030SDEC, Mark Croxton)