A jQuery plugin for populating HTML elements from JSON data, including support for arrays of objects, conditional display, value formatting, lazy loading, templates, and dynamic attribute/class assignment.
Create the plugin instance directly:
$(function(){varmyFill=new$.akFillFromJSON($('#element'),options,arg);myFill.foo_public_method();});Or initialize through the jQuery plugin interface:
$(function(){$('#myHolder').akFillFromJSON(options,arg);});$("#myHolder").akFillFromJSON({readOnly: false,joinBy: ", ",replaceArr: [],lazyLoading: false,recordCount: null,append: false,data: {},primaryKey: "",fromFieldEvent: false,template: null,beforeObj: function(fieldName,dataObj,settings){},callback: function(fieldName,$placedItem,dataObj,settings){},showLog: false});| Option | Type | Default | Description |
|---|---|---|---|
readOnly | Boolean | false | Controls whether setElemVal is used on form elements. |
joinBy | String | ", " | Separator used when an array contains strings that need to be joined. |
replaceArr | Array | [] | Replacements applied to string values. Use ["replaceThis", "withThis"] or multiple replacement pairs. |
lazyLoading | Boolean | false | Loads elements up to the height of the screen and loads more as the user scrolls. |
recordCount | Number/null | null | Number of records to load at a time. With lazyLoading, additional records load when the last visible record becomes visible. |
append | Boolean | false | Appends additional records instead of clearing existing records. |
data | Object | {} | Data source used to populate the holder. |
primaryKey | String | "" | Primary key used when processing records. |
fromFieldEvent | Boolean | false | Prevents toggleFieldRow from triggering. |
template | Object/null | null | Forces a specific template for each object in an array. |
beforeObj | Function | — | Called before processing each object in an array. Can modify settings.template to force a template. |
callback | Function | — | Called after each object is appended. |
showLog | Boolean/Array | false | Enables logging for non-akForm elements. Can be true, false, or an array such as ["display", "fields"]. |
The plugin uses a field-name convention based on the JSON object's keys.
For a field named title, the following classes can be used:
<spanclass="titleVal"></span><divclass="titleDiv"></div><divclass="not-titleDiv"></div>Displays an element when the field has a value and hides it when the field has no value.
<divclass="titleDiv"><spanclass="titleVal"></span></div>Displays an element when the field has no value and hides it when the field has a value.
<divclass="not-titleDiv">
No title available.
</div>Populates the contents of a standard element.
<spanclass="titleVal"></span>For <img>, <iframe>, <embed>, and <video>, [field]Val populates the src attribute.
<imgclass="imageVal">Prefixes the value with data-path.
<imgclass="imageVal"
data-path="/assets/images/"
>Result:
/assets/images/<value>
Appends additional text after the value.
<imgclass="imageVal"
data-path="/assets/images/"
data-append=".jpg"
>Result:
/assets/images/<value>.jpg
For <object>, [field]Val populates the data attribute.
<objectclass="documentVal"></object>data-path and data-append are supported in the same way as media elements.
Populates an anchor's href.
<aclass="websiteVal-link">Website</a>Supports:
data-pathdata-append
Creates an email link:
<aclass="emailVal-email"></a>Resulting href:
mailto:<value>
Creates a telephone link:
<aclass="phoneVal-tel"></a>Resulting href:
tel:<value>
Creates a social URL using data-base.
<aclass="usernameVal-social"
data-base="https://example.com/"
></a>Resulting href:
https://example.com/<value>
Assigns the field value to the element's CSS width.
If the value is numeric, the hidden and d-none classes are removed.
If the value is not numeric, hidden and d-none are added.
<divclass="progressVal-width"></div>Populates an input's value.
<inputclass="usernameVal-inpV">Populates an input's name and assigns the field value as a class.
<inputclass="usernameVal-inpN">Populates the element's title property.
<spanclass="titleVal-title"></span>Creates a data-* attribute using a slugified field name.
<divclass="userVal-attr"></div>The resulting attribute follows the pattern:
data-user="..."Adds the field value as a CSS class.
<divclass="statusVal-class"></div>The plugin supports formatter suffixes on [field]Val.
Converts a string to camel case.
<spanclass="nameVal.camelCase"></span>Converts a string to Pascal case.
<spanclass="nameVal.pascalCase"></span>Converts a string to alphanumeric characters only.
<spanclass="nameVal.alphaNumify"></span>Converts a string to a slug.
<spanclass="nameVal.slugify"></span>Converts a string to HTML, including converting line breaks to <br>.
<divclass="descriptionVal.toHTML"></div>Converts HTML into text only.
<divclass="descriptionVal.toText"></div>Formats a number with commas.
<spanclass="amountVal.toNumber-commas"></span>Example:
5123456.345
becomes:
5,123,456.345
Formats a number as money.
<spanclass="amountVal.toNumber-money"></span>Appends % to the value.
<spanclass="completionVal.toNumber-percent"></span>Sets the element's HTML to a block representing the color value.
<divclass="colorVal.toColorBlock"></div>Creates a Font Awesome icon from the field value and adds the required fa/fa- prefixes.
<iclass="iconVal.toFAicon"></i>Converts an email address into a mailto<a> element.
<spanclass="emailVal.toEmailLink"></span>The [field]Val[data-format] functionality converts a value to a formated date.
Example:
<spanclass="birthDateVal"
data-format="I"
></span>Example formats:
| Format | Result |
|---|---|
I | 9/4/1986 |
L | 09/04/1986 |
LL | September 4, 1986 |
The plugin can populate holders from arrays of objects.
Clear the current records:
$("#myHolder").akFillFromJSON("clear");Load more records:
$("#myHolder").akFillFromJSON("more");Get the array data associated with the closest index:
varobjData=$(this).akFillFromJSON("getData");Get the plugin instance:
varmyObj=$("#myHolder").akFillFromJSON("get");The instance can then be used directly:
myObj.clearItems();myObj.fillMore();Alternatively, an instance can be retrieved by holder ID:
varmyObj=getAKpluginInstance("fills",holderID);Specifies the object key used to assign the data-id attribute to each generated item.
<ulid="myHolder"
data-assign="id"
></ul>Defines the placeholder used while content is being loaded.
The value can be:
- An existing object
- HTML
- An image path
Example:
<divid="myHolder"
data-placeholder="/assets/blah.jpg"
></div>Defines the template used to create each item.
The value can be:
- An existing object
- HTML
- An element ID such as
#myTemplate
The container is cloned when used as a template.
<divid="myHolder"
data-template="#myTemplate"
></div>A basic array-of-objects setup can look like this:
<divclass="demoModulesDiv"><h4>Lab Modules</h4><ulclass="fa-ul demoModules-holder"><liclass="demoModules-item"><spanclass="fa-li"><iclass="far fa-caret-right"></i></span><strongclass="moduleTitleVal"></strong><spanclass="moduleDescriptionDiv">
-
<spanclass="moduleDescriptionVal"></span></span></li></ul></div>Given an object such as:
{moduleTitle: "Example Module",moduleDescription: "An example module description."}The plugin maps:
moduleTitle → .moduleTitleVal
moduleDescription → .moduleDescriptionVal
The moduleDescriptionDiv wrapper can additionally be shown or hidden based on whether moduleDescription contains a value.
$("#myHolder").akFillFromJSON({data: {modules: [{id: 1,moduleTitle: "Module One",moduleDescription: "First module."},{id: 2,moduleTitle: "Module Two",moduleDescription: "Second module."}]},primaryKey: "id",lazyLoading: true,recordCount: 10,callback: function(fieldName,$placedItem,dataObj,settings){// Custom processing after each object is appended.}});Called before processing each object in an array.
beforeObj: function(fieldName,dataObj,settings){// settings.template can be changed here.}This can be used to dynamically select a template:
beforeObj: function(fieldName,dataObj,settings){if(dataObj.featured){settings.template="#featuredTemplate";}}Called after each object has been appended.
callback: function(fieldName,$placedItem,dataObj,settings){// Custom processing for the newly inserted item.}Enable lazy loading with:
$("#myHolder").akFillFromJSON({lazyLoading: true});Use recordCount to control the number of records loaded at a time:
$("#myHolder").akFillFromJSON({lazyLoading: true,recordCount: 10});When lazy loading is enabled, additional records are loaded as the user reaches the end of the currently visible records.
Set append to true to retain existing records and append additional records:
$("#myHolder").akFillFromJSON({append: true});$("#myHolder").akFillFromJSON("clear");$("#myHolder").akFillFromJSON("more");$("#myHolder").akFillFromJSON("getData");$("#myHolder").akFillFromJSON("get");varmyObj=$("#myHolder").akFillFromJSON("get");myObj.clearItems();myObj.fillMore();| Pattern | Purpose |
|---|---|
[field]Div | Show when a value exists |
not-[field]Div | Show when a value does not exist |
[field]Val | Populate element content |
[field]Val-link | Populate href |
[field]Val-email | Create mailto: link |
[field]Val-tel | Create tel: link |
[field]Val-social | Build social URL from data-base |
[field]Val-width | Set CSS width |
[field]Val-inpV | Set input value |
[field]Val-inpN | Set input name/class |
[field]Val-title | Set title |
[field]Val-attr | Set data-* attribute |
[field]Val-class | Add CSS class |
[field]Val.camelCase | Convert to camel case |
[field]Val.pascalCase | Convert to Pascal case |
[field]Val.alphaNumify | Keep alphanumeric characters |
[field]Val.slugify | Convert to slug |
[field]Val.toHTML | Convert text to HTML |
[field]Val.toText | Convert HTML to text |
[field]Val.toNumber-commas | Format number with commas |
[field]Val.toNumber-money | Format as money |
[field]Val.toNumber-percent | Append % |
[field]Val.toColorBlock | Render a color block |
[field]Val.toFAicon | Render Font Awesome icon |
[field]Val.toEmailLink | Render email as a link |
[field]Val[data-format] | Format dates |
- The plugin is designed around jQuery selectors and class-based field binding.
- Array-of-object rendering supports templates, callbacks, placeholders, lazy loading, and incremental loading.
- Font Awesome formatting depends on the corresponding Font Awesome classes being available in the project.