jsGrid Lightweight Grid jQuery Plugin
Project site js-grid.com
jsGrid is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components.
Table of contents
- Demos
- Installation
- Basic Usage
- Configuration
- Grid Fields
- Methods
- Callbacks
- Grid Controller
- Validation
- Localization
- Sorting Strategies
- Load Strategies
- Load Indication
- Requirement
- Compatibility
Demos
See Demos on project site.
Sample projects showing how to use jsGrid with the most popular backend technologies
- PHP - https://github.com/tabalinas/jsgrid-php
- ASP.NET WebAPI - https://github.com/tabalinas/jsgrid-webapi
- Express (NodeJS) - https://github.com/tabalinas/jsgrid-express
- Ruby on Rail - https://github.com/tabalinas/jsgrid-rails
- Django (Python) - https://github.com/tabalinas/jsgrid-django
Installation
Install jsgrid with bower:
$ bower install js-grid
Find jsGrid cdn links here.
Basic Usage
Ensure that jQuery library of version 1.8.3 or later is included.
Include jsgrid.min.js
, jsgrid-theme.min.css
, and jsgrid.min.css
files into the web page.
Create grid applying jQuery plugin jsGrid
with grid config as follows:
;
Configuration
The config object may contain following options (default values are specified below):
fields: data: autoload: false controller: loadData: $noop insertItem: $noop updateItem: $noop deleteItem: $noop width: "auto" height: "auto" heading: true filtering: false inserting: false editing: false selecting: true sorting: false paging: false pageLoading: false { ... } { ... } { ... } noDataContent: "Not found" confirmDeleting: true deleteConfirm: "Are you sure?" pagerContainer: null pageIndex: 1 pageSize: 20 pageButtonCount: 15 pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}" pagePrevText: "Prev" pageNextText: "Next" pageFirstText: "First" pageLastText: "Last" pageNavigatorNextText: "..." pageNavigatorPrevText: "..." { ... } invalidMessage: "Invalid data entered!" loadIndication: true loadIndicationDelay: 500 loadMessage: "Please, wait..." loadShading: true { ... } { ... } updateOnResize: true rowRenderer: null headerRowRenderer: null filterRowRenderer: null insertRowRenderer: null editRowRenderer: null pagerRenderer: null
fields
An array of fields (columns) of the grid.
Each field has general options and specific options depending on field type.
General options peculiar to all field types:
type: "" name: "" title: "" align: "" width: 100 visible: true css: "" headercss: "" filtercss: "" insertcss: "" editcss: "" filtering: true inserting: true editing: true sorting: true sorter: "string" { ... } { ... } { ... } { ... } { ... } { ... } { ... } { ... } cellRenderer: null validate: null
- type is a string key of field (
"text"|"number"|"checkbox"|"select"|"textarea"|"control"
) in fields registryjsGrid.fields
(the registry can be easily extended with custom field types). - name is a property of data item associated with the column.
- title is a text to be displayed in the header of the column. If
title
is not specified, thename
will be used instead. - align is alignment of text in the cell. Accepts following values
"left"|"center"|"right"
. - width is a width of the column.
- visible is a boolean specifying whether to show a column or not. (version added: 1.3)
- css is a string representing css classes to be attached to the table cell.
- headercss is a string representing css classes to be attached to the table header cell. If not specified, then css is attached instead.
- filtercss is a string representing css classes to be attached to the table filter row cell. If not specified, then css is attached instead.
- insertcss is a string representing css classes to be attached to the table insert row cell. If not specified, then css is attached instead.
- editcss is a string representing css classes to be attached to the table edit row cell. If not specified, then css is attached instead.
- filtering is a boolean specifying whether or not column has filtering (
filterTemplate()
is rendered andfilterValue()
is included in load filter object). - inserting is a boolean specifying whether or not column has inserting (
insertTemplate()
is rendered andinsertValue()
is included in inserting item). - editing is a boolean specifying whether or not column has editing (
editTemplate()
is rendered andeditValue()
is included in editing item). - sorting is a boolean specifying whether or not column has sorting ability.
- sorter is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry
jsGrid.sortStrategies
(the registry can be easily extended with custom sorting functions). Sorting function has the signaturefunction(value1, value2) { return -1|0|1; }
. - headerTemplate is a function to create column header content. It should return markup as string, DomNode or jQueryElement.
- itemTemplate is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is
function(value, item)
, wherevalue
is a value of column property of data item, anditem
is a row data item. - filterTemplate is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement.
- insertTemplate is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement.
- editTemplate is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is
function(value, item)
, wherevalue
is a value of column property of data item, anditem
is a row data item. - filterValue is a function returning the value of filter property associated with the column.
- insertValue is a function returning the value of inserting item property associated with the column.
- editValue is a function returning the value of editing item property associated with the column.
- cellRenderer is a function to customize cell rendering. The function signature is
function(value, item)
, wherevalue
is a value of column property of data item, anditem
is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table celltd
. - validate is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the Validation section.
Specific field options depends on concrete field type. Read about build-in fields in Grid Fields section.
data
An array of items to be displayed in the grid. The option should be used to provide static data. Use the controller
option to provide non static data.
false
)
autoload (default A boolean value specifying whether controller.loadData
will be called when grid is rendered.
controller
An object or function returning an object with the following structure:
loadData: $noop insertItem: $noop updateItem: $noop deleteItem: $noop
- loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when
pageLoading
istrue
instead of object the structure{ data: [items], itemsCount: [total items count] }
should be returned). Accepts filter parameter including current filter options and paging parameters whenpageLoading
istrue
. - insertItem is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object.
- updateItem is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object.
- deleteItem is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object.
Read more about controller interface in Grid Controller section.
"auto"
)
width (default: Specifies the overall width of the grid.
Accepts all value types accepting by jQuery.width
.
"auto"
)
height (default: Specifies the overall height of the grid including the pager.
Accepts all value types accepting by jQuery.height
.
true
)
heading (default: A boolean value specifies whether to show grid header or not.
false
)
filtering (default: A boolean value specifies whether to show filter row or not.
false
)
inserting (default: A boolean value specifies whether to show inserting row or not.
false
)
editing (default: A boolean value specifies whether editing is allowed.
true
)
selecting (default: A boolean value specifies whether to highlight grid rows on hover.
false
)
sorting (default: A boolean value specifies whether sorting is allowed.
false
)
paging (default: A boolean value specifies whether data is displayed by pages.
false
)
pageLoading (default: A boolean value specifies whether to load data by page.
When pageLoading
is true
the loadData
method of controller accepts filter
parameter with two additional properties pageSize
and pageIndex
.
rowClass
A string or a function specifying row css classes.
A string contains classes separated with spaces.
A function has signature function(item, itemIndex)
. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces.
rowClick
A function handling row click. Accepts single argument with following structure:
item // data item itemIndex // data item index event // jQuery event
By default rowClick
performs row editing when editing
is true
.
rowDoubleClick
A function handling row double click. Accepts single argument with the following structure:
item // data item itemIndex // data item index event // jQuery event
"Not found"
)
noDataContent (default A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when data
is an empty array.
true
)
confirmDeleting (default A boolean value specifying whether to ask user to confirm item deletion.
"Are you sure?"
)
deleteConfirm (default A string or a function returning string specifying delete confirmation message to be displayed to the user.
A function has the signature function(item)
and accepts item to be deleted.
null
)
pagerContainer (default A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to null
, the pager is rendered at the bottom of the grid.
1
)
pageIndex (default An integer value specifying current page index. Applied only when paging
is true
.
20
)
pageSize (default An integer value specifying the amount of items on the page. Applied only when paging
is true
.
15
)
pageButtonCount (default An integer value specifying the maximum amount of page buttons to be displayed in the pager.
pagerFormat
A string specifying pager format.
The default value is "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"
There are placeholders that can be used in the format:
first // link to first pageprev // link to previous pagepages // page linksnext // link to next pagelast // link to last pagepageIndex // current page indexpageCount // total amount of pagesitemCount // total amount of items
"Next"
)
pageNextText (default A string specifying the text of the link to the next page.
"Prev"
)
pagePrevText (default A string specifying the text of the link to the previous page.
"First"
)
pageFirstText (default A string specifying the text of the link to the first page.
"Last"
)
pageLastText (default A string specifying the text of the link to the last page.
"..."
)
pageNavigatorNextText (default A string specifying the text of the link to move to next set of page links, when total amount of pages more than pageButtonCount
.
"..."
)
pageNavigatorPrevText (default A string specifying the text of the link to move to previous set of page links, when total amount of pages more than pageButtonCount
.
"Invalid data entered!"
)
invalidMessage (default A string specifying the text of the alert message, when invalid data was entered.
invalidNotify
A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function.
The function accepts a single argument with the following structure:
item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" }
In the following example error messages are printed in the console instead of alerting:
;
true
)
loadIndication (default A boolean value specifying whether to show loading indication during controller operations execution.
500
)
loadIndicationDelay (default An integer value specifying the delay in ms before showing load indication. Applied only when loadIndication
is true
.
"Please, wait..."
)
loadMessage (default A string specifying the text of loading indication panel. Applied only when loadIndication
is true
.
true
)
loadShading (default A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when loadIndication
is true
.
loadIndicator
An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods show
and hide
.
show
is called on each loading start. hide
method is called on each loading finish. Read more about custom load indicator in the Load Indication section.
loadStrategy
An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing).
There are two build-in load strategies: DirectLoadingStrategy
and PageLoadingStrategy
. Load strategy depends on pageLoading
option value.
For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the Load Strategies section.
true
)
updateOnResize (default A boolean value specifying whether to refresh grid on window resize event.
null
)
rowRenderer (default A function to customize row rendering. The function signature is function(item, itemIndex)
, where item
is row data item, and itemIndex
is the item index.
The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
null
)
headerRowRenderer (default A function to customize grid header row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
null
)
filterRowRenderer (default A function to customize grid filter row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
null
)
insertRowRenderer (default A function to customize grid inserting row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
null
)
editRowRenderer (default A function to customize editing row rendering. The function signature is function(item, itemIndex)
, where item
is row data item, and itemIndex
is the item index.
The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
null
)
pagerRenderer (default version added: 1.2
A function to customize pager rendering. The function accepts a single argument with the following structure:
pageIndex // index of the currently opened page pageCount // total amount of grid pages
The function should return markup as a string, jQueryElement or DomNode representing the pager.
If pagerRenderer
is specified, then pagerFormat
option will be ignored.
Grid Fields
All fields supporting by grid are stored in jsGrid.fields
object, where key is a type of the field and the value is the field class.
jsGrid.fields
contains following build-in fields:
text: ... // simple text input number: ... // number input select: ... // select control checkbox: ... // checkbox input textarea: ... // textarea control (renders textarea for inserting and editing and text input for filtering) control: ... // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row
Each build-in field can be easily customized with general configuration properties described in fields section and custom field-specific properties described below.
text
Text field renders <input type="text">
in filter, inserting and editing rows.
Custom properties:
autosearch: true // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4)
number
Number field renders <input type="number">
in filter, inserting and editing rows.
Custom properties:
sorter: "number" // uses sorter for numbers align: "right" // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4)
select
Select field renders <select>
control in filter, inserting and editing rows.
Custom properties:
align: "center" // center text alignment autosearch: true // triggers searching when the user changes the selected item in the filter items: // an array of items for select valueField: "" // name of property of item to be used as value textField: "" // name of property of item to be used as displaying value selectedIndex: -1 // index of selected item by default valueType: "number|string" // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4)
If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value.
For instance the simple select field config may look like:
name: "Country" type: "select" items: "" "United States" "Canada" "United Kingdom"
or more complex with items as objects:
name: "Country" type: "select" items: Name: "" Id: 0 Name: "United States" Id: 1 Name: "Canada" Id: 2 Name: "United Kingdom" Id: 3 valueField: "Id" textField: "Name"
valueType
defines whether the field value should be converted to a number or returned as a string.
The value of the option is determined automatically depending on the data type of valueField
of the first item, but it can be overridden.
checkbox
Checkbox field renders <input type="checkbox">
in filter, inserting and editing rows.
Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked).
Custom properties:
sorter: "number" // uses sorter for numbers align: "center" // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter
textarea
Textarea field renders <textarea>
in inserting and editing rows and <input type="text">
in filter row.
Custom properties:
autosearch: true // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4)
control
Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row.
Custom properties:
editButton: true // show edit button deleteButton: true // show delete button clearFilterButton: true // show clear filter button modeSwitchButton: true // show switching filtering/inserting button align: "center" // center content alignment width: 50 // default column width is 50px filtering: false // disable filtering for column inserting: false // disable inserting for column editing: false // disable editing for column sorting: false // disable sorting for column searchModeButtonTooltip: "Switch to searching" // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting" // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit" // tooltip of edit item button deleteButtonTooltip: "Delete" // tooltip of delete item button searchButtonTooltip: "Search" // tooltip of search button clearFilterButtonTooltip: "Clear filter" // tooltip of clear filter button insertButtonTooltip: "Insert" // tooltip of insert button updateButtonTooltip: "Update" // tooltip of update item button cancelEditButtonTooltip: "Cancel edit" // tooltip of cancel editing button
Custom Field
If you need a completely custom field, the object jsGrid.fields
can be easily extended.
In this example we define new grid field date
:
var { jsGridField;}; MyDateFieldprototype = css: "date-field" // redefine general property 'css' align: "center" // redefine general property 'align' myCustomProperty: "foo" // custom property { return date1 - date2; } { return value; } { return this_insertPicker = ; } { return this_editPicker = ; } { return this_insertPicker; } { return this_editPicker; }; jsGridfieldsdate = MyDateField;
To have all general grid field properties custom field class should inherit jsGrid.Field
class or any other field class.
Here itemTemplate
just returns the string representation of a date.
insertTemplate
and editTemplate
create jQuery UI datePicker for inserting and editing row.
Of course jquery ui library should be included to make it work.
insertValue
and editValue
return date to insert and update items accordingly.
We also defined date specific sorter.
Now, our new field date
can be used in the grid config as follows:
fields: ... type: "date" myCustomProperty: "bar" ...
Methods
jsGrid methods could be called with jsGrid
jQuery plugin or directly.
To use jsGrid plugin to call a method, just call jsGrid
with method name and required parameters as next arguments:
// calling method with jQuery plugin;
To call method directly you need to retrieve grid instance or just create grid with the constructor:
// retrieve grid instance from element datavar grid = data"JSGrid"; // create grid with the constructorvar grid = ... ; // call method directlygrid;
cancelEdit()
Cancels row editing.
;
Promise
clearFilter(): Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed.
;
clearInsert()
Clears current inserting row.
;
Promise
deleteItem(item|$row|rowNode): Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed.
item|$row|rowNode is the reference to the item or the row jQueryElement or the row DomNode.
// delete row by item reference; // delete row by jQueryElement; // delete row by DomNode;
destroy()
Destroys the grid and brings the Node to its original state.
;
editItem(item|$row|rowNode)
Sets grid editing row.
item|$row|rowNode is the reference to the item or the row jQueryElement or the row DomNode.
// edit row by item reference; // edit row by jQueryElement; // edit row by DomNode;
Object
getFilter(): Get grid filter as a plain object.
var filter = ;
Object
getSorting(): version added: 1.2
Get grid current sorting params as a plain object with the following format:
field // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order
var sorting = ;
fieldOption(fieldName|fieldIndex, optionName, [optionValue])
version added: 1.3
Gets or sets the value of a field option.
fieldName|fieldIndex is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used).
optionName is the name of the field option.
optionValue is the new option value to set.
If optionValue
is not specified, then the value of the field option optionName
will be returned.
// hide the field "ClientName"; // get width of the 2nd fieldvar secondFieldOption = ;
Promise
insertItem([item]): Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed.
item is the item to pass to controller.insertItem
.
If item
is not specified the data from inserting row will be inserted.
// insert item from inserting row; // insert item;
Promise
loadData([filter]): Loads data calling corresponding controller.loadData
method.
Returns jQuery promise resolved when data loading is completed.
It preserves current sorting and paging unlike the search
method .
filter is a filter to pass to controller.loadData
.
If filter
is not specified the current filter (filtering row values) will be applied.
// load data with current grid filter; // loadData with custom filter;
openPage(pageIndex)
Opens the page of specified index.
pageIndex is one-based index of the page to open. The value should be in range from 1 to [total amount of pages].
option(optionName, [optionValue])
Gets or sets the value of an option.
optionName is the name of the option.
optionValue is the new option value to set.
If optionValue
is not specified, then the value of the option optionName
will be returned.
// turn off paging; // get current page indexvar pageIndex = ;
refresh()
Refreshes the grid. Renders the grid body and pager content, recalculates sizes.
;
Promise
render(): Performs complete grid rendering. If option autoload
is true
calls controller.loadData
. The state of the grid like current page and sorting is retained.
Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved.
;
reset()
Resets the state of the grid. Goes to the first data page, resets sorting, and then calls refresh
.
;
jQueryElement
rowByItem(item): version added: 1.3
Gets the row jQuery element corresponding to the item.
item is the item corresponding to the row.
var $row = ;
Promise
search([filter]): Performs filtering of the grid.
Returns jQuery promise resolved when data loading is completed.
It resets current sorting and paging unlike the loadData
method.
filter is a filter to pass to controller.loadData
.
If filter
is not specified the current filter (filtering row values) will be applied.
// search with current grid filter; // search with custom filter;
showPrevPages()
Shows previous set of pages, when total amount of pages more than pageButtonCount
.
;
showNextPages()
Shows next set of pages, when total amount of pages more than pageButtonCount
.
;
Promise
sort(sortConfig|field, [order]): Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed.
sortConfig is the plain object of the following structure { field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }
field is the field to sort by. It could be zero-based field index or field name or field reference
order is the sorting order. Accepts the following values: "asc"|"desc"
If order
is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or "asc"
for sorting by another field.
When grid data is loaded by pages (pageLoading
is true
) sorting calls controller.loadData
with sorting parameters. Read more in Grid Controller section.
// sorting grid by first field; // sorting grid by field "Name" in descending order; // sorting grid by myField in ascending order ;
Promise
updateItem([item|$row|rowNode], [editedItem]): Updates item and row of the grid. Returns jQuery promise resolved when update is completed.
item|$row|rowNode is the reference to the item or the row jQueryElement or the row DomNode.
editedItem is the changed item to pass to controller.updateItem
.
If item|$row|rowNode
is not specified then editing row will be updated.
If editedItem
is not specified the data from editing row will be taken.
// update currently editing row; // update currently editing row with specified data; // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference);
jsGrid.locale(localeName|localeConfig)
version added: 1.4
Set current locale of all grids.
localeName|localeConfig is the name of the supported locale (see available locales) or a custom localization config. Find more information on custom localization config in Localization.
// set French localejsGrid;
jsGrid.setDefaults(config)
Set default options for all grids.
jsGrid;
jsGrid.setDefaults(fieldName, config)
Set default options of the particular field.
jsGrid;
Callbacks
jsGrid allows to specify a callback function to be executed on a particular event.
The following callbacks are supported:
{} // before controller.loadData {} // on done of controller.loadData {} // after grid initialization {} // before controller.insertItem {} // on done of controller.insertItem {} // before controller.updateItem {} // on done of controller.updateItem {} // before controller.deleteItem {} // on done of controller.deleteItem {} // after item validation, in case data is invalid {} // on fail of any controller call {} // before changing the grid option {} // after changing the grid option {} // after changing the current page {} // before grid refresh {} // after grid refresh
onDataLoading
Fires before data loading.
Has the following arguments:
grid // grid instance filter // loading filter object
Cancel Data Loading
version added: 1.2
To cancel data loading set args.cancel = true
.
In the following example loading is canceled when the filter has empty 'name' field:
;
onDataLoaded
Fires after data loading.
Has the following arguments:
grid // grid instance data // load result (array of items or data structure for loading by page scenario)
In the following example the loaded data is written to the browser console.
;
onInit
version added: 1.5
Fires after grid initialization right before rendering. Usually used to get grid instance.
Has the following arguments:
grid // grid instance
In the following example we get the grid instance on initialization:
var gridInstance; ;
onError
Fires when controller handler promise failed.
Has the following arguments:
grid // grid instance args // an array of arguments provided to fail promise handler
onItemDeleting
Fires before item deletion.
Has the following arguments:
grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index
Cancel Item Deletion
version added: 1.2
To cancel item deletion set args.cancel = true
. This allows to do a validation before performing the actual deletion.
In the following example the deletion of items marked as protected
is canceled:
;
onItemDeleted
Fires after item deletion.
Has the following arguments:
grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index
onItemEditing
version added: 1.4
Fires before item editing.
Has the following arguments:
grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index
Cancel Item Editing
To cancel item editing set args.cancel = true
. This allows to prevent row from editing conditionally.
In the following example the editing of the row for item with 'ID' = 0 is canceled:
;
onItemInserting
Fires before item insertion.
Has the following arguments:
grid // grid instance item // inserting item
Cancel Item Insertion
version added: 1.2
To cancel item insertion set args.cancel = true
. This allows to do a validation before performing the actual insertion.
In the following example insertion of items with the 'name' specified is allowed:
;
onItemInserted
Fires after item insertion.
Has the following arguments:
grid // grid instance item // inserted item
onItemInvalid
Fired when item is not following validation rules on inserting or updating.
Has the following arguments:
grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" }
The following handler prints errors on the console
;
onItemUpdating
Fires before item update.
Has the following arguments:
grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing
Cancel Item Update
version added: 1.2
To cancel item update set args.cancel = true
. This allows to do a validation before performing the actual update.
In the following example update of items with the 'name' specified is allowed:
;
onItemUpdated
Fires after item update.
Has the following arguments:
grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing
onOptionChanging
Fires before grid option value change.
Has the following arguments:
grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option
onOptionChanged
Fires after grid option value change.
Has the following arguments:
grid // grid instance option // name of changed option value // changed option value
onPageChanged
version added: 1.5
Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method openPage
, or changing the option pageIndex
.
Has the following arguments:
grid // grid instance pageIndex // current page index
In the following example we print the current page index in the browser console once it has been changed:
;
onRefreshing
Fires before grid refresh.
Has the following arguments:
grid // grid instance
onRefreshed
Fires after grid refresh.
Has the following arguments:
grid // grid instance
Grid Controller
The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods.
By default grid has an empty controller and can work with static array of items stored in option data
.
A controller should implement the following methods:
{ ... } { ... } { ... } { ... }
Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise.
For instance the controller for typical REST service might look like:
{ return $; } { return $; } { return $; } { return $; }
Promise|dataResult
loadData(filter): Called on data loading.
filter contains all filter parameters of fields with enabled filtering
When pageLoading
is true
and data is loaded by page, filter
includes two more parameters:
pageIndex // current page index pageSize // the size of page
When grid sorting is enabled, filter
includes two more parameters:
sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc"
Method should return dataResult
or jQuery promise that will be resolved with dataResult
.
dataResult depends on pageLoading
. When pageLoading
is false
(by default), then data result is a plain javascript array of objects.
If pageLoading
is true
data result should have following structure
data // array of items itemsCount // total items amount in storage
Promise|insertedItem
insertItem(item): Called on item insertion.
Method should return insertedItem
or jQuery promise that will be resolved with insertedItem
.
If no item is returned, inserting item will be used as inserted item.
item is the item to be inserted.
Promise|updatedItem
updateItem(item): Called on item update.
Method should return updatedItem
or jQuery promise that will be resolved with updatedItem
.
If no item is returned, updating item will be used as updated item.
item is the item to be updated.
Promise
deleteItem(item): Called on item deletion.
If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed.
item is the item to be deleted.
Validation
version added: 1.4
Field Validation Config
validate
option of the field can have 4 different value types string|Object|Array|function
:
validate: "validatorName"
validatorName - is a string key of the validator in the jsGrid.validators
registry. The registry can be easily extended. See available built-in validators here.
In the following example the required
validator is applied:
;
validate: validationConfig
validateConfig - is a plain object of the following structure:
validator: string|, // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function}
In the following example the range
validator is applied with custom validation message and range provided in parameters:
;
validate: validateArray
validateArray - is an array of validators. It can contain
string
- validator nameObject
- validator configuration of structure{ validator, message, param }
function
- validation function asfunction(value, item)
In the following example the field has three validators: required
, range
, and a custom function validator:
;
validate: function(value, item, param)
The parameters of the function:
value
- entered value of the fielditem
- editing/inserting itemparam
- a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects)
In the following example the field has custom validation function:
;
Built-in Validators
The jsGrid.validators
object contains all built-in validators. The key of the hash is a validator name and the value is the validator config.
jsGrid.validators
contains the following build-in validators:
- required - the field value is required
- rangeLength - the length of the field value is limited by range (the range should be provided as an array in
param
field of validation config) - minLength - the minimum length of the field value is limited (the minimum value should be provided in
param
field of validation config) - maxLength - the maximum length of the field value is limited (the maximum value should be provided in
param
field of validation config) - pattern - the field value should match the defined pattern (the pattern should be provided as a string regexp in
param
field of validation config) - range - the value of the number field is limited by range (the range should be provided as an array in
param
field of validation config) - min - the minimum value of the number field is limited (the minimum should be provided in
param
field of validation config) - max - the maximum value of the number field is limited (the maximum should be provided in
param
field of validation config)
Custom Validators
To define a custom validator just add it to the jsGrid.validators
object.
In the following example a custom validator time
is registered:
jsGridvalidatorstime = message: "Please enter a valid time, between 00:00 and 23:59" { return /^{1,2}$/; }
Localization
version added: 1.4
Current locale can be set for all grids on the page with the jsGrid.locale(localeName)
method.
New custom locale can be added to jsGrid.locales
hash like the following:
jsGridlocalesmy_lang = // localization config goes here ...;
Here is how localization config looks like for Spanish i18n/es.js.
Find all available locales here.
Sorting Strategies
All supported sorting strategies are stored in jsGrid.sortStrategies
object, where key is a name of the strategy and the value is a sortingFunction
.
jsGrid.sortStrategies
contains following build-in sorting strategies:
string: ... // string sorter number: ... // number sorter date: ... // date sorter numberAsString: ... // numbers are parsed before comparison
sortingFunction is a sorting function with the following format:
{ ifvalue1 < value2 return -1; // return negative value when first is less than second ifvalue1 === value2 return 0; // return zero if values are equal ifvalue1 > value2 return 1; // return positive value when first is greater than second}
Custom Sorting Strategy
If you need a custom sorting strategy, the object jsGrid.sortStrategies
can be easily extended.
In this example we define new sorting strategy for our client objects:
// clients arrayvar clients = Index: 1 Name: "John" Age: 25 ...; // sort clients by name and then by agejsGridsortStrategies { var client1 = clientsindex1; var client2 = clientsindex2; return client1Name || client1Age - client2Age;};
Now, our new sorting strategy client
can be used in the grid config as follows:
fields: ... name: "Index" sorter: "client" ...
Worth to mention, that if you need particular sorting only once, you can just inline sorting function in sorter
not registering the new strategy:
fields: ... name: "Index" { var client1 = clientsindex1; var client2 = clientsindex2; return client1Name || client1Age - client2Age; } ...
Load Strategies
The behavior of the grid regarding data source interaction is defined by load strategy.
The load strategy has the following methods:
{} // returns the index of the first displayed item {} // returns the index of the last displayed item {} // returns the total amount of grid items {} // handles opening of the particular page {} // returns additional parameters for controller.loadData method {} // handles sorting of data in the grid, should return a Promise {} // handles grid refresh on grid reset with 'reset' method call, should return a Promise {} // handles the finish of loading data by controller.loadData {} // handles the finish of inserting item by controller.insertItem {} // handles the finish of deleting item by controller.deleteItem
There are two build-in load strategies: DirectLoadingStrategy (for pageLoading=false
) and PageLoadingStrategy (for pageLoading=true
).
DirectLoadingStrategy
DirectLoadingStrategy is used when loading by page is turned off (pageLoading=false
).
It provides the following behavior:
- firstDisplayIndex returns the index of the first item on the displayed page
- lastDisplayIndex returns the index of the last item on the displayed page
- itemsCount returns the actual amount of all the loaded items
- openPage refreshes the grid to render items of current page
- loadParams returns empty object, since no extra load params are needed
- sort sorts data items and refreshes the grid calling
grid.refresh
- reset calls
grid.refresh
method to refresh the grid - finishLoad puts the data coming from
controller.loadData
into the optiondata
of the grid - finishInsert pushes new inserted item into the option
data
and refreshes the grid - finishDelete removes deleted item from the option
data
and resets the grid
PageLoadingStrategy
PageLoadingStrategy is used when data is loaded to the grid by pages (pageLoading=true
).
It provides the following behavior:
- firstDisplayIndex returns 0, because all loaded items displayed on the current page
- lastDisplayIndex returns the amount of loaded items, since data loaded by page
- itemsCount returns
itemsCount
provided bycontroller.loadData
(read more in section controller.loadData) - openPage calls
grid.loadData
to load data for the current page - loadParams returns an object with the structure
{ pageIndex, pageSize }
to provide server with paging info - sort calls
grid.loadData
to load sorted data from the server - reset calls
grid.loadData
method to refresh the data - finishLoad saves
itemsCount
returned by server and puts thedata
into the optiondata
of the grid - finishInsert calls
grid.search
to reload the data - finishDelete calls
grid.search
to reload the data
Custom LoadStrategy
The option loadStrategy
allows to specify a custom load strategy to customize the behavior of the grid.
The easiest way to do it is to inherit from existing strategy.
By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item.
var { jsGridloadStrategiesDirectLoadingStrategy;}; MyCustomDirectLoadStrategyprototype = ; MyCustomDirectLoadStrategyprototype { var grid = this_grid; grid; grid;}; // use custom strategy in grid config;
Load Indication
By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the loadIndicator
option.
Set an object or a function returning an object supporting the following interface:
{ ... } // called on loading start { ... } // called on loading finish
This simple example prints messages to console instead of showing load indicator:
loadIndicator: { console; } { console; }
If loadIndicator
is a function, it accepts the config of load indicator in the following format:
container // grid container div message // the loading message is a value of the option loadMessage shading // the boolean value defining whether to show shading. This is a value of the option loadShading
The similar example printing messages to console shows how to configure loading indicator with a function returning an object:
{ return { console; } { console; } ; }
Customization of loading indicator is useful, when you want to use any external load indicator that is used for all other ajax requests on the page.
This example shows how to use spin.js to indicate loading:
{ var container = configcontainer0; var spinner = ; return { spinner; } { spinner; } ; }
Requirement
jQuery (1.8.3 or later)
Compatibility
Desktop
- Chrome
- Safari
- Firefox
- Opera 15+
- IE 8+
Mobile
- Safari for iOS
- Chrome for Android
- IE10 for WP8