Skip to content

Latest commit

History

24 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

akFillFromJSON

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.

Usage

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);});

Initialization Options

$("#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});
OptionTypeDefaultDescription
readOnlyBooleanfalseControls whether setElemVal is used on form elements.
joinByString", "Separator used when an array contains strings that need to be joined.
replaceArrArray[]Replacements applied to string values. Use ["replaceThis", "withThis"] or multiple replacement pairs.
lazyLoadingBooleanfalseLoads elements up to the height of the screen and loads more as the user scrolls.
recordCountNumber/nullnullNumber of records to load at a time. With lazyLoading, additional records load when the last visible record becomes visible.
appendBooleanfalseAppends additional records instead of clearing existing records.
dataObject{}Data source used to populate the holder.
primaryKeyString""Primary key used when processing records.
fromFieldEventBooleanfalsePrevents toggleFieldRow from triggering.
templateObject/nullnullForces a specific template for each object in an array.
beforeObjFunctionCalled before processing each object in an array. Can modify settings.template to force a template.
callbackFunctionCalled after each object is appended.
showLogBoolean/ArrayfalseEnables logging for non-akForm elements. Can be true, false, or an array such as ["display", "fields"].

Classes and Field Binding

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>

Conditional Display

[field]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>

.not-[field]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>

Value Population

[field]Val

Populates the contents of a standard element.

<spanclass="titleVal"></span>

Media Elements

For <img>, <iframe>, <embed>, and <video>, [field]Val populates the src attribute.

<imgclass="imageVal">

data-path

Prefixes the value with data-path.

<imgclass="imageVal"
data-path="/assets/images/"
>

Result:

/assets/images/<value>

data-append

Appends additional text after the value.

<imgclass="imageVal"
data-path="/assets/images/"
data-append=".jpg"
>

Result:

/assets/images/<value>.jpg

<object>

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.

Links

[field]Val-link

Populates an anchor's href.

<aclass="websiteVal-link">Website</a>

Supports:

  • data-path
  • data-append

[field]Val-email

Creates an email link:

<aclass="emailVal-email"></a>

Resulting href:

mailto:<value>

[field]Val-tel

Creates a telephone link:

<aclass="phoneVal-tel"></a>

Resulting href:

tel:<value>

[field]Val-social

Creates a social URL using data-base.

<aclass="usernameVal-social"
data-base="https://example.com/"
></a>

Resulting href:

https://example.com/<value>

Specialized Value Classes

[field]Val-width

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>

[field]Val-inpV

Populates an input's value.

<inputclass="usernameVal-inpV">

[field]Val-inpN

Populates an input's name and assigns the field value as a class.

<inputclass="usernameVal-inpN">

[field]Val-title

Populates the element's title property.

<spanclass="titleVal-title"></span>

[field]Val-attr

Creates a data-* attribute using a slugified field name.

<divclass="userVal-attr"></div>

The resulting attribute follows the pattern:

data-user="..."

[field]Val-class

Adds the field value as a CSS class.

<divclass="statusVal-class"></div>

String Formatting

The plugin supports formatter suffixes on [field]Val.

.camelCase

Converts a string to camel case.

<spanclass="nameVal.camelCase"></span>

.pascalCase

Converts a string to Pascal case.

<spanclass="nameVal.pascalCase"></span>

.alphaNumify

Converts a string to alphanumeric characters only.

<spanclass="nameVal.alphaNumify"></span>

.slugify

Converts a string to a slug.

<spanclass="nameVal.slugify"></span>

.toHTML

Converts a string to HTML, including converting line breaks to <br>.

<divclass="descriptionVal.toHTML"></div>

.toText

Converts HTML into text only.

<divclass="descriptionVal.toText"></div>

.toNumber-commas

Formats a number with commas.

<spanclass="amountVal.toNumber-commas"></span>

Example:

5123456.345

becomes:

5,123,456.345

.toNumber-money

Formats a number as money.

<spanclass="amountVal.toNumber-money"></span>

.toNumber-percent

Appends % to the value.

<spanclass="completionVal.toNumber-percent"></span>

.toColorBlock

Sets the element's HTML to a block representing the color value.

<divclass="colorVal.toColorBlock"></div>

.toFAicon

Creates a Font Awesome icon from the field value and adds the required fa/fa- prefixes.

<iclass="iconVal.toFAicon"></i>

.toEmailLink

Converts an email address into a mailto<a> element.

<spanclass="emailVal.toEmailLink"></span>

Date Formatting

The [field]Val[data-format] functionality converts a value to a formated date.

Example:

<spanclass="birthDateVal"
data-format="I"
></span>

Example formats:

FormatResult
I9/4/1986
L09/04/1986
LLSeptember 4, 1986

Arrays of Objects

The plugin can populate holders from arrays of objects.

Methods

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);

Holder Attributes

data-assign

Specifies the object key used to assign the data-id attribute to each generated item.

<ulid="myHolder"
data-assign="id"
></ul>

data-placeholder

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>

data-template

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>

HTML Setup

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.

Example Initialization

$("#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.}});

Lifecycle Hooks

beforeObj

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";}}

callback

Called after each object has been appended.

callback: function(fieldName,$placedItem,dataObj,settings){// Custom processing for the newly inserted item.}

Lazy Loading

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.

Append Mode

Set append to true to retain existing records and append additional records:

$("#myHolder").akFillFromJSON({append: true});

Public API Summary

jQuery API

$("#myHolder").akFillFromJSON("clear");$("#myHolder").akFillFromJSON("more");$("#myHolder").akFillFromJSON("getData");$("#myHolder").akFillFromJSON("get");

Instance API

varmyObj=$("#myHolder").akFillFromJSON("get");myObj.clearItems();myObj.fillMore();

Quick Reference

PatternPurpose
[field]DivShow when a value exists
not-[field]DivShow when a value does not exist
[field]ValPopulate element content
[field]Val-linkPopulate href
[field]Val-emailCreate mailto: link
[field]Val-telCreate tel: link
[field]Val-socialBuild social URL from data-base
[field]Val-widthSet CSS width
[field]Val-inpVSet input value
[field]Val-inpNSet input name/class
[field]Val-titleSet title
[field]Val-attrSet data-* attribute
[field]Val-classAdd CSS class
[field]Val.camelCaseConvert to camel case
[field]Val.pascalCaseConvert to Pascal case
[field]Val.alphaNumifyKeep alphanumeric characters
[field]Val.slugifyConvert to slug
[field]Val.toHTMLConvert text to HTML
[field]Val.toTextConvert HTML to text
[field]Val.toNumber-commasFormat number with commas
[field]Val.toNumber-moneyFormat as money
[field]Val.toNumber-percentAppend %
[field]Val.toColorBlockRender a color block
[field]Val.toFAiconRender Font Awesome icon
[field]Val.toEmailLinkRender email as a link
[field]Val[data-format]Format dates

Notes

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

About

Fill DOM objects with JSON data based on tag attributes.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages