jsxgrid
v2.8.0
Published
Lightweight data grid jQuery plugin, with a built-in extra field set (avatars, JSON editor, select, collapsible textarea, datetime picker, row selection). A maintained fork of jsGrid.
Readme
jsxgrid
jsxgrid 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, and is tunable and allows to customize appearance and components. On top of that base, it ships with a set of extra fields built in: avatars, a JSON editor, a collapsible textarea, a datetime picker (with range filtering), a row-selection column with a bulk action, and a computed summary footer.
Credits
jsxgrid is a fork of jsGrid by Artem Tabalin, which provided the original grid engine and design this project is built on. jsGrid saw no releases after 2016; jsxgrid continues it — cherry-picked fixes from PRs that never got merged upstream (memory leak on grid destroy, a CSP-unsafe inline style, a couple of correctness fixes), merges in a set of extra fields that used to be a separate package (xfields), and is maintained going forward by Mikhail Kremza.
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 the demos/ folder in this repo — demos/xfields.html in particular exercises every extra
field together on one grid.
Installation
npm install jsxgridor via Composer, as an npm-mirrored asset:
composer require npm-asset/jsxgridThe build is split into independent pieces - include only what you actually use:
dist/jsxgrid.js(or.min.js) - the engine. Always required.dist/jsxgrid-fields.js- the native field types (text,number,select,checkbox,textarea,control). Skip this if you only use the extra fields below.dist/jsxgrid-xfields.js- the extra fields (Xcheckbox,Xselect, ...). Does not needjsxgrid-fields.js- every extra field extends the engine's baseFieldclass directly, not the native field types.dist/jsxgrid.cssanddist/jsxgrid-theme.cssfor styling.
Individual fields (native or extra) can also be loaded one at a time from dist/fields/ instead of pulling in a whole bundle.
dist/jsxgrid.js must load before any field file or locale file (dist/i18n/jsgrid-*.js) - they all register
themselves onto the jsGrid global. Getting the order wrong doesn't throw an uncaught error: each of those
files logs a specific console.error naming itself and returns without doing anything, and a grid that ends
up using an unregistered field type logs a console.warn and silently falls back to the plain base field
(no filter/insert/edit UI for that column) instead of failing to render. Check the console first if a field
or a locale seems to have no effect.
Basic Usage
Ensure that jQuery (version 3.0 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:
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
filtering: true,
editing: true,
sorting: true,
paging: true,
data: db.clients,
fields: [
{ name: "Name", type: "text", width: 150 },
{ name: "Age", type: "number", width: 50 },
{ name: "Address", type: "text", width: 200 },
{ name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" },
{ name: "Married", type: "checkbox", title: "Is Married", sorting: false },
{ type: "control" }
]
});
Configuration
The config object may contain following options (default values are specified below):
{
fields: [],
data: [],
locale: null, // per-instance locale, see Localization section
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,
sortField: null, // initial sort, see below
sortOrder: null, // "asc" | "desc", defaults to "asc" when sortField is set
paging: false,
pageLoading: false,
insertRowLocation: "bottom",
rowClass: function(item, itemIndex) { ... },
rowClick: function(args) { ... },
rowDoubleClick: function(args) { ... },
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: "...",
pageSizeSelectOptions: [10, 20, 50, 100], // see "Pager page-size selector"
pageSizeSelectClass: "jsgrid-page-size-select",
exportChunkSize: 500, // rows per controller request when exporting all (see exportRows)
invalidNotify: function(args) { ... }
invalidMessage: "Invalid data entered!",
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
loadIndicator: function(config) { ... }
loadStrategy: function(config) { ... }
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",
headerTemplate: function() { ... },
itemTemplate: function(value, item) { ... },
filterTemplate: function() { ... },
insertTemplate: function() { ... },
editTemplate: function(value, item) { ... },
filterValue: function() { ... },
insertValue: function() { ... },
editValue: function() { ... },
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
titleis not specified, thenamewill 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), wherevalueis a value of column property of data item, anditemis 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), wherevalueis a value of column property of data item, anditemis 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), wherevalueis a value of column property of data item, anditemis 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.
autoload (default false)
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
pageLoadingistrueinstead of object the structure{ data: [items], itemsCount: [total items count] }should be returned). Accepts filter parameter including current filter options and paging parameters whenpageLoadingistrue. - 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.
width (default: "auto")
Specifies the overall width of the grid.
Accepts all value types accepting by jQuery.width.
height (default: "auto")
Specifies the overall height of the grid including the pager.
Accepts all value types accepting by jQuery.height.
heading (default: true)
A boolean value specifies whether to show grid header or not.
filtering (default: false)
A boolean value specifies whether to show filter row or not.
inserting (default: false)
A boolean value specifies whether to show inserting row or not.
editing (default: false)
A boolean value specifies whether editing is allowed.
selecting (default: true)
A boolean value specifies whether to highlight grid rows on hover.
sorting (default: false)
A boolean value specifies whether sorting is allowed.
sortField / sortOrder (default: null / null)
jsxgrid extension, not in upstream jsGrid
Sets the initial sort, applied once at construction - baked into the first render/load, unlike calling
sort() after creating the grid (which would trigger its own extra refresh/reload). sortField accepts
anything sort() does: a field name, a zero-based field index, or a field reference. sortOrder is
"asc" or "desc", defaulting to "asc" when sortField is set. Requires sorting: true.
With pageLoading: true, the initial sortField/sortOrder are sent to controller.loadData like any
other sort (same as clicking a sortable header would) - sorting is the server's job there, jsxgrid never
re-sorts the page client-side on top of it. For static in-memory data (not loaded through a controller),
the array is sorted immediately, before the first render. For a controller-backed grid without
pageLoading, there's nothing to sort yet at construction time (data arrives later) - it's sorted once,
client-side, as soon as the first loadData() call resolves.
$("#grid").jsGrid({
sorting: true,
sortField: "Name",
sortOrder: "desc",
...
});
paging (default: false)
A boolean value specifies whether data is displayed by pages.
pageLoading (default: false)
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.
insertRowLocation (default: "bottom")
Specifies the location of an inserted row within the grid.
When insertRowLocation is "bottom" the new row will appear at the bottom of the grid. When set to "top", the new row will appear at the top.
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
}
noDataContent (default "Not found")
A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when data is an empty array.
confirmDeleting (default true)
A boolean value specifying whether to ask user to confirm item deletion.
deleteConfirm (default "Are you sure?")
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.
pagerContainer (default null)
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.
pageIndex (default 1)
An integer value specifying current page index. Applied only when paging is true.
pageSize (default 20)
An integer value specifying the amount of items on the page. Applied only when paging is true.
pageButtonCount (default 15)
An integer value specifying the maximum amount of page buttons to be displayed in the pager.
jsxgrid extension, not in upstream jsGrid: the visible window of page buttons is centered on
the current page (e.g. with pageButtonCount: 5 on page 8, the pager shows 6 7 8 9 10) and
re-centers on every page change, clamped to the actual page range at either end. Upstream jsGrid
only shifts the window once the current page falls outside it, so the last button in the window was
never clickable through to the next page without clicking the ... nav link first - this fixes
that. The ... nav links (showPrevPages/showNextPages) still work as before, jumping the
visible window by a full pageButtonCount without changing the current page.
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 page
{prev} // link to previous page
{pages} // page links
{next} // link to next page
{last} // link to last page
{pageIndex} // current page index
{pageCount} // total amount of pages
{itemCount} // total amount of items
{pageSize} // page-size <select> - jsxgrid extension, see "Pager page-size selector" below
The built-in English default doesn't show {itemCount}, but every one of the 19 shipped locales
(src/i18n/*.js) appends a translated "found records" label with it to the end of its own pagerFormat
(same line as the page links), e.g. ... Найдено записей: {itemCount} for ru. With
pageLoading: true it is the total reported by the server (itemsCount), not the size of the current page.
To drop it for a localized grid, override pagerFormat without it (see the example below).
Pager page-size selector
jsxgrid extension, not in upstream jsGrid
Off by default - the built-in English default pagerFormat doesn't include {pageSize}, so a plain
new jsGrid.Grid(...)/$.jsGrid(...) with no locale set is unaffected. Every one of jsxgrid's 19
shipped locales (src/i18n/*.js) does include it in their own pagerFormat, translated - so
jsGrid.locale("ru") (or any other shipped locale) or a grid's own locale: "ru" option turns the
selector on as part of picking that locale, no separate opt-in needed. To turn it back off for a
localized grid, or to opt in without any locale at all, set pagerFormat yourself:
$("#grid").jsGrid({
paging: true,
pagerFormat: "Показывать по {pageSize} строк Pages: {first} {prev} {pages} {next} {last}",
...
});
To disable it on a grid that's using a locale (locale: "ru" or jsGrid.locale("ru")), override
pagerFormat with the same text minus {pageSize}:
$("#grid").jsGrid({
locale: "ru",
paging: true,
pagerFormat: "Страницы: {first} {prev} {pages} {next} {last} {pageIndex} из {pageCount}",
...
});
{pageSize} renders a <select> of page-size choices; picking one calls grid.option("pageSize", ...),
which already refreshes and reloads like any other pageSize change. The current pageSize is always
selectable even if it isn't one of the configured choices (e.g. set directly in the grid config).
| Option | Default | Description |
|---|---|---|
| pageSizeSelectOptions | [10, 20, 50, 100] | The list of page sizes offered in the <select>. |
| pageSizeSelectClass | "jsgrid-page-size-select" | CSS class on the <select> element. |
Unlike the page-number links, the pager stays visible even when there's only one page, as long as
pagerFormat uses {pageSize} - a page-size selector is still useful with a small dataset (e.g. to
shrink it, or to pre-set it before more data arrives), unlike page navigation with nothing to navigate to.
pageNextText (default "Next")
A string specifying the text of the link to the next page.
pagePrevText (default "Prev")
A string specifying the text of the link to the previous page.
pageFirstText (default "First")
A string specifying the text of the link to the first page.
pageLastText (default "Last")
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.
invalidMessage (default "Invalid data entered!")
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:
$("#grid").jsGrid({
...
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.field + ": " + error.message;
});
console.log(messages);
}
...
});
loadIndication (default true)
A boolean value specifying whether to show loading indication during controller operations execution.
loadIndicationDelay (default 500)
An integer value specifying the delay in ms before showing load indication. Applied only when loadIndication is true.
loadMessage (default "Please, wait...")
A string specifying the text of loading indication panel. Applied only when loadIndication is true.
loadShading (default true)
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.
updateOnResize (default true)
A boolean value specifying whether to refresh grid on window resize event.
rowRenderer (default null)
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.
headerRowRenderer (default null)
A function to customize grid header row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr.
filterRowRenderer (default null)
A function to customize grid filter row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr.
insertRowRenderer (default null)
A function to customize grid inserting row.
The function should return markup as a string, jQueryElement or DomNode representing table row tr.
editRowRenderer (default null)
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.
pagerRenderer (default null)
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
}
Extra fields
Fields below ship with jsxgrid on top of the base set. Every one of them (except XRowSelectField, which
never filters) supports a shared defaultSelected convention: a value used to preset the filter control the
first time its filter row is rendered, then reset to null so it doesn't keep overriding what the user
searches for afterwards.
Every one of them (except XRowSelectField and Xcontrol, neither of which has a value to insert) also
supports defaultValue: a value used to prefill the insert row's control. Unlike defaultSelected, this
is not reset after use — it's applied every time a fresh insert row is built (including after
clearInsert()), so a new row keeps starting from the same default until you change it in code.
As of Xtext/Xnumber/Xcontrol, every native field type (text, number, select, checkbox,
textarea, control) now has an X-branded equivalent — the native set (dist/jsxgrid-fields.js) is kept
around as legacy/optional, with new work going into the X set going forward.
Xtext
Drop-in replacement for text.
| Option | Default | Description |
|---|---|---|
| readOnly | false | Whether the input is readonly. |
| defaultSelected | null | A string to preset the filter input with. |
| defaultValue | null | A string to prefill the insert row with. |
Xnumber
Drop-in replacement for number. Standalone — does not extend Xtext, only jsGrid.Field directly, same as
every other X-field.
| Option | Default | Description |
|---|---|---|
| readOnly | false | Whether the input is readonly. |
| numberRange | false | When true, the filter renders two number inputs (from/to) instead of one, and filterValue() returns {from, to}. |
| defaultSelected | null | A number (or numeric string) to preset the filter input with. When numberRange is true, pass {from, to} instead. |
| defaultValue | null | A number (or numeric string) to prefill the insert row with. Not supported when numberRange is true (insertTemplate() doesn't render a range picker). |
Xcheckbox
Drop-in replacement for checkbox. Returns 1/0 instead of true/false, which avoids a lot of backend
type-coercion headaches (especially with databases).
| Option | Default | Description |
|---|---|---|
| defaultSelected | null | 0/1/true/false to preset the filter checkbox as unchecked/checked; leave null for the default indeterminate ("any") state. |
| defaultValue | null | 0/1/true/false to prefill the insert row checkbox as unchecked/checked. |
XimgField
Text field that previews its value as an <img>.
| Option | Default | Description |
|---|---|---|
| fm_callback | null | function(control) — if set, insert/edit renders a button instead of a text input, and clicking it calls this callback with the jQuery-wrapped control so you can wire up your own file manager/picker. |
| editButtonText | 'Open FM' | Text for that button. |
| defaultSelected | null | A string to preset the filter input with. |
| defaultValue | null | A string to prefill the insert row with (the plain-text-input mode; still stored even in fm_callback button mode). |
Xselect
Drop-in replacement for select, plus:
| Option | Default | Description |
|---|---|---|
| pseudoElement | null | An extra item unshifted to the start of the filter dropdown (e.g. an "any" option). Shape must match your items (object for object-items, or a {[textField]:'', [valueField]:null}-like item for array items). |
| select2 | null | Config object passed to select2 on the filter control (width is always forced to 100%). Applied via setTimeout(0) so the control is attached to the DOM first. |
| defaultSelected | null | A value to preselect in the filter, matched against items by valueField (or by array index / object key if there's no valueField). |
| defaultValue | null | A value to preselect in the insert row, matched the same way. |
Xtextarea
Long text is collapsed and expandable on click.
| Option | Default | Description |
|---|---|---|
| maxShowSymbols | 50 | Values longer than this are truncated with ...; click the cell to expand. |
| defaultSelected | null | A string to preset the filter input with. |
| defaultValue | null | A string to prefill the insert row with. |
Xjsoneditor
Edits/views a JSON value through jsoneditor (required peer
dependency — must be loaded on the page, e.g. via CDN, or Xjsoneditor will throw when you try to open
the editor).
| Option | Default | Description |
|---|---|---|
| templates | [] | Forwarded to jsoneditor's templates option. |
| editText | 'Editor' | Text of the button shown in view mode. |
| closeText | 'Save' | Close-button text used when opening the editor for insert/edit. |
| defaultSelected | null | A string to preset the (text-based) filter input with — the filter matches against the raw JSON string, not parsed values. |
| defaultValue | null | A JSON value (object, or an already-stringified string) to prefill the insert row with. |
XRowSelectField
A checkbox-per-row selection column with an optional header action button. filtering is hardcoded to
false, so there's no filter row and no defaultSelected support.
| Option | Default | Description |
|---|---|---|
| buttonText | '' | Header button text. Header button is hidden entirely if left empty. |
| selectedItemsAction | no-op | function(selectedItems) — called when the header button is clicked. Override this to implement your bulk action. |
Field instance also exposes:
selectItem(item)/unselectItem(item)— used internally by the row checkboxes.unselectAll()— clearsselectedItemsand unchecks every row checkbox for this field. Call it at the end of yourselectedItemsActionif you want selection to reset after the action runs.
XDateTimeField
Date/datetime field backed by a native <input type="datetime-local"> (or whatever datePickerType you set).
| Option | Default | Description |
|---|---|---|
| datePickerType | 'datetime-local' | Any native <input> date/time type (date, datetime-local, time, ...). |
| dateRange | false | When true, the filter renders two date inputs (from/to) instead of one, and filterValue() returns {from, to}. |
| options | built-in Intl.DateTimeFormat options | Passed to toLocaleDateString() when rendering the item view. Empty values render as an empty string. |
| defaultSelected | null | A value (matching datePickerType's input format) to preset the filter with. When dateRange is true, pass {from, to} instead. |
| defaultValue | null | A value (matching datePickerType's input format) to prefill the insert row with. Not currently supported when dateRange is true (insertTemplate() doesn't render a range picker). |
Xcontrol
Drop-in replacement for control. Already standalone even as a native field (extends jsGrid.Field
directly), so this is a straight rename — no behavior changes, no defaultSelected (nothing to filter by).
Same custom properties as control, plus an opt-in export button:
| Option | Default | Description |
|---|---|---|
| exportButton | false | Adds an export button to the header cell. If the grid pages and has more than one page, it opens a small menu to choose the volume — the current page or all records (exportRows); otherwise it exports everything right away. |
| exportHandler | null | function(rows, {scope, grid, field}) — receives the rows to export (scope is "page" or "all"). Build your own file here (e.g. an .xlsx via SheetJS). Without it a UTF-8 CSV (with BOM, ;-delimited) is downloaded. |
| exportFileName | "export.csv" | File name of the default CSV download. |
| exportButtonTooltip, exportPageText, exportAllText | "Export", "Current page", "All records" | Texts; translated in every shipped locale. |
| exportButtonClass, exportMenuClass, exportMenuItemClass | "jsgrid-export-button", "jsgrid-export-menu", "jsgrid-export-menu-item" | CSS classes (the icon and menu styles live in jsxgrid-theme.css). |
{
type: "Xcontrol",
exportButton: true,
exportHandler: function (rows, info) {
// info.scope === "page" | "all"; info.grid is the grid instance
buildAndSaveWorkbook(rows);
}
}
popup.basic
A minimal, jQuery-only modal used by Xjsoneditor (and available for your own use) as jsGrid.popup /
jsGrid.popupBasic:
jsGrid.popup(formContentOrElement, {
heading: "Title", // optional
closeText: "Close", // optional
styles: "...", // optional, overrides the injected default CSS (injected once per page)
onClose: function (popup) { /* ... */ }
});
You can swap in your own modal implementation entirely by overwriting jsGrid.popup.
jsGridSummaryPlugin
Patches $.fn.jsGrid so any field can define a summary(data) function; the results are rendered as a
<tfoot> row (.jsgrid-summary-footer) after every grid refresh:
{
name: "Age", type: "number",
summary: function (data) {
var total = data.reduce(function (s, i) { return s + (parseFloat(i.Age) || 0); }, 0);
return "Sum: " + total; // rendered via .html(), so markup is allowed
}
}
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 MyDateField = function(config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
css: "date-field", // redefine general property 'css'
align: "center", // redefine general property 'align'
myCustomProperty: "foo", // custom property
sorter: function(date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function(value) {
return new Date(value).toDateString();
},
insertTemplate: function(value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function(value) {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
},
insertValue: function() {
return this._insertPicker.datepicker("getDate").toISOString();
},
editValue: function() {
return this._editPicker.datepicker("getDate").toISOString();
}
});
jsGrid.fields.date = 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
$("#grid").jsGrid("methodName", param1, param2);
To call method directly you need to retrieve grid instance or just create grid with the constructor:
// retrieve grid instance from element data
var grid = $("#grid").data("JSGrid");
// create grid with the constructor
var grid = new jsGrid.Grid($("#grid"), { ... });
// call method directly
grid.methodName(param1, param2);
cancelEdit()
Cancels row editing.
$("#grid").jsGrid("cancelEdit");
clearFilter(): Promise
Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed.
$("#grid").jsGrid("clearFilter").done(function() {
console.log("filtering completed");
});
clearInsert()
Clears current inserting row.
$("#grid").jsGrid("clearInsert");
deleteItem(item|$row|rowNode): Promise
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
$("#grid").jsGrid("deleteItem", item);
// delete row by jQueryElement
$("#grid").jsGrid("deleteItem", $(".specific-row"));
// delete row by DomNode
$("#grid").jsGrid("deleteItem", rowNode);
destroy()
Destroys the grid and brings the Node to its original state.
$("#grid").jsGrid("destroy");
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
$("#grid").jsGrid("editItem", item);
// edit row by jQueryElement
$("#grid").jsGrid("editItem", $(".specific-row"));
// edit row by DomNode
$("#grid").jsGrid("editItem", rowNode);
getFilter(): Object
Get grid filter as a plain object.
var filter = $("#grid").jsGrid("getFilter");
getSorting(): Object
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 = $("#grid").jsGrid("getSorting");
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"
$("#grid").jsGrid("fieldOption", "ClientName", "visible", false);
// get width of the 2nd field
var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width");
insertItem([item]): Promise
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
$("#grid").jsGrid("insertItem");
// insert item
$("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() {
console.log("insertion completed");
});
loadData([filter]): Promise
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
$("#grid").jsGrid("loadData");
// loadData with custom filter
$("#grid").jsGrid("loadData", { Name: "John" }).done(function() {
console.log("data loaded");
});
exportData([options])
Transforms the grid data into the specified output type.
Output can be formatted, filtered or modified by providing options.
Currently only supports CSV output.
//Basic export
var csv = $("#grid").jsGrid("exportData");
//Full Options
var csv = $("#grid").jsGrid("exportData", {
type: "csv", //Only CSV supported
subset: "all" | "visible", //Visible will only output the currently displayed page
delimiter: "|", //If using csv, the character to seperate fields
includeHeaders: true, //Include header row in output
encapsulate: true, //Surround each field with qoutation marks; needed for some systems
newline: "\r\n", //Newline character to use
//Takes each item and returns true if it should be included in output.
//Executed only on the records within the given subset above.
filter: function(item){return true},
//Transformations are a way to modify the display value of the output.
//Provide a key of the field name, and a function that takes the current value.
transformations: {
"Married": function(value){
if (value === true){
return "Yes"
}
else{
return "No"
}
}
}
});
exportRows([options])
jsxgrid extension, not in upstream jsGrid
Returns a promise of the rows to export. Unlike exportData (synchronous, only what is already in memory)
it can also fetch the rows that aren't loaded: with server paging (pageLoading: true) the grid replays its
last load through controller.loadData, page by page, exportChunkSize rows per request, until
itemsCount rows are collected. No separate "export" endpoint is needed: the controller is called exactly
as for a normal load (same filter and sorting as the last load, only pageIndex/pageSize differ).
$("#grid").jsGrid("exportRows", {
scope: "page" | "all", // "page" (default): what is on screen; "all": everything under the current filter/sorting
chunkSize: 500 // optional, overrides the grid's exportChunkSize for this call
}).done(function (rows) {
// rows are the items as the controller returned them
});
The grid's own data, pager and loading state are left alone (only the load indicator is shown while
fetching), and onDataLoading/onDataLoaded are not fired. onDataExporting receives {scope}.
For a grid that doesn't page on the server "all" is simply all of data, and no controller call happens.
exportCsv([options])
jsxgrid extension, not in upstream jsGrid
exportRows rendered as CSV: a promise of a string. Options: scope, chunkSize (as above), delimiter
(default ";"), newline, includeHeaders, encapsulate. Columns are the visible fields that have a name
(includeInDataExport: false leaves one out); select-like fields (items with valueField/textField, or an
object map) are written as their text. Unlike exportData the values are taken by field name, so the item's
key order doesn't matter.
exportFields()
jsxgrid extension, not in upstream jsGrid
The fields that make up an export, in column order: visible ones that have a name (so no buttons), minus
those with includeInDataExport: false. Use it, together with exportCellValue, to build your own file
(e.g. an .xlsx) in an exportHandler.
exportCellValue(item, field)
jsxgrid extension, not in upstream jsGrid
The value of one cell for an export: the item's value as it is (a number stays a number, which is what a
spreadsheet wants), except that a select-like field (items with valueField/textField, or an object map)
gives its text instead of the code, and a missing value gives "". exportCsv uses it too (turning the
result into a string).
exportHandler: function (rows, info) {
var fields = info.grid.exportFields();
var aoa = [fields.map(function (f) { return f.title || f.name; })].concat(rows.map(function (row) {
return fields.map(function (f) { return info.grid.exportCellValue(row, f); });
}));
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), "Export");
XLSX.writeFile(wb, "export.xlsx");
}
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
$("#grid").jsGrid("option", "paging", false);
// get current page index
var pageIndex = $("#grid").jsGrid("option", "pageIndex");
refresh()
Refreshes the grid. Renders the grid body and pager content, recalculates sizes.
$("#grid").jsGrid("refresh");
render(): Promise
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.
$("#grid").jsGrid("render").done(function() {
console.log("rendering completed and data loaded");
});
reset()
Resets the state of the grid. Goes to the first data page, resets sorting, and then calls refresh.
$("#grid").jsGrid("reset");
rowByItem(item): jQueryElement
version added: 1.3
Gets the row jQuery element corresponding to the item.
item is the item corresponding to the row.
var $row = $("#grid").jsGrid("rowByItem", item);
search([filter]): Promise
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
$("#grid").jsGrid("search");
// search with custom filter
$("#grid").jsGrid("search", { Name: "John" }).done(function() {
console.log("filtering completed");
});
showPrevPages()
Shows previous set of pages, when total amount of pages more than pageButtonCount.
$("#grid").jsGrid("showPrevPages");
showNextPages()
Shows next set of pages, when total amount of pages more than pageButtonCount.
$("#grid").jsGrid("showNextPages");
sort(sortConfig|field, [order]): Promise
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
$("#grid").jsGrid("sort", 0);
// sorting grid by field "Name" in descending order
$("#grid").jsGrid("sort", { field: "Name", order: "desc" });
// sorting grid by myField in ascending order
$("#grid").jsGrid("sort", myField, "asc").done(function() {
console.log("sorting completed");
});
updateItem([item|$row|rowNode], [editedItem]): Promise
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
$("#grid").jsGrid("updateItem");
// update currently editing row with specified data
$("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 });
// update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference)
$("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() {
console.log("update completed");
});
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 locale
jsGrid.locale("fr");
jsGrid.setDefaults(config)
Set default options for all grids.
jsGrid.setDefaults({
filtering: true,
inserting: true
});
jsGrid.setDefaults(fieldName, config)
Set default options of the particular field.
jsGrid.setDefaults("text", {
width: 150,
css: "text-field-cls"
});
Callbacks
jsGrid allows to specify a callback function to be executed on a particular event.
The following callbacks are supported:
{
onDataLoading: function(args) {}, // before controller.loadData
onDataLoaded: function(args) {}, // on done of controller.loadData
onDataExporting: function() {}, // before data export
onInit: function(args) {}, // after grid initialization
onItemInserting: function(args) {}, // before controller.insertItem
onItemInserted: function(args) {}, // on done of controller.insertItem
onItemUpdating: function(args) {}, // before controller.updateItem
onItemUpdated: function(args) {}, // on done of controller.updateItem
onItemDeleting: function(args) {}, // before controller.deleteItem
onItemDeleted: function(args) {}, // on done of controller.deleteItem
onItemInvalid: function(args) {}, // after item validation, in case data is invalid
onError: function(args) {}, // on fail of any controller call
onOptionChanging: function(args) {}, // before changing the grid option
onOptionChanged: function(args) {}, // after changing the grid option
onPageChanged: function(args) {}, // after changing the current page
onRefreshing: function(args) {}, // before grid refresh
onRefreshed: function(args) {}, // 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:
$("#grid").jsGrid({
...
onDataLoading: function(args) {
// cancel loading data if 'name' is empty
if(args.filter.name === "") {
args.cancel = true;
}
}
});
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.
$("#grid").jsGrid({
...
onDataLoaded: function(args) {
console.log(args.data);
}
});
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;
$("#grid").jsGrid({
...
onInit: function(args) {
gridInstance = args.grid;
}
});
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:
$("#grid").jsGrid({
...
onItemDeleting: function(args) {
// cancel deletion of the item with 'protected' field
if(args.item.protected) {
args.cancel = true;
}
}
});
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:
$("#grid").jsGrid({
...
onItemEditing: function(args) {
// cancel editing of the row of item with field 'ID' = 0
if(args.item.ID === 0) {
args.cancel = true;
}
}
});
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:
$("#grid").jsGrid({
...
onItemInserting: function(args) {
// cancel insertion of the item with empty 'name' field
if(args.item.name === "") {
args.cancel = true;
alert("Specify the name of the item!");
}
}
});
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
$("#grid").jsGrid({
...
onItemInvalid: function(args) {
// prints [{ field: "Name", message: