Easy Tutorial
❮ Plugins Dt Tree Jeasyui Tree Tree6 ❯

jQuery EasyUI DataGrid and Tree Plugin - Datagrid DataGrid



Extends from $.fn.panel.defaults. Overrides the default defaults with $.fn.datagrid.defaults.

The DataGrid displays data in a tabular format and provides rich support for selecting, sorting, grouping, and editing data. The design goal of the DataGrid is to reduce development time and not require developers to have specific knowledge. It is lightweight yet feature-rich. Its features include cell merging, multi-column headers, frozen columns and footers, and more.

Dependencies

Usage

Create a DataGrid from an existing table element, defining columns, rows, and data in the HTML.

<table class="easyui-datagrid">
    <thead>
        <tr>
            <th data-options="field:'code'">Code</th>
            <th data-options="field:'name'">Name</th>
            <th data-options="field:'price'">Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>001</td><td>name1</td><td>2323</td>
        </tr>
        <tr>
            <td>002</td><td>name2</td><td>4612</td>
        </tr>
    </tbody>
</table>

Create a DataGrid with the <table> tag. The nested <th> tags define the columns in the table.

<table class="easyui-datagrid" style="width:400px;height:250px"
    data-options="url:'datagrid_data.json',fitColumns:true,singleSelect:true">
    <thead>
        <tr>
            <th data-options="field:'code',width:100">Code</th>
            <th data-options="field:'name',width:100">Name</th>
            <th data-options="field:'price',width:100,align:'right'">Price</th>
        </tr>
    </thead>
</table>

You can also create a DataGrid using JavaScript.

<table id="dg"></table>
$('#dg').datagrid({
    url:'datagrid_data.json',
    columns:[[
        {field:'code',title:'Code',width:100},
        {field:'name',title:'Name',width:100},
        {field:'price',title:'Price',width:100,align:'right'}
    ]]
});

Query data with some parameters.

$('#dg').datagrid('load', {
    name: 'easyui',
    address: 'ho'
});

Update the front-end data after changing data on the server.

$('#dg').datagrid('reload');    // reload the current page data

DataGrid Properties

This property extends from the panel. Below are properties added for the DataGrid.

Name Type Description Default Value
columns array The DataGrid column configuration object. See column properties for more details. undefined
frozenColumns array Same as the columns property, but these columns will be frozen on the left. undefined
fitColumns boolean When set to true, it will automatically expand or shrink the column sizes to fit the grid width and prevent horizontal scrolling. false
resizeHandle string The position to resize columns, available values are: 'left', 'right', 'both'. When set to 'right', the user can resize the column by dragging the right edge of the column header. Available since version 1.3.2. right
autoRowHeight boolean Defines if the row height is set based on the content of the row. Setting to false can improve loading performance. true
toolbar array,selector The toolbar in the DataGrid panel header. Possible values: <br>1. Array, each tool option is the same as linkbutton. <br>2. Selector, just the toolbar. <br><br>Define the toolbar in a <div> tag: $('#dg').datagrid({<br>    toolbar: '#tb'<br>});<br><div id="tb"><br><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true"></a><br><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-help',plain:true"></a><br></div>Define the toolbar with an array: $('#dg').datagrid({<br>    toolbar: [{<br>        iconCls: 'icon-edit',<br>        handler: function(){alert('edit')}<br>    },'-',{<br>        iconCls: 'icon-help',<br>        handler: function(){alert('help')}<br>    }]<br>}); null
striped boolean When set to true, it will stripe the rows. (i.e., alternate rows have different background colors) false
method string The method type to request remote data. post
nowrap boolean When set to true, it will display the data in a single line. Setting to true can improve loading performance. true
idField string Indicates which field is the identifier field. null
url string The URL to request data from a remote site. null
data array,object The data to be loaded. Available since version 1.3.2. <br>Example code: $('#dg').datagrid({<br>    data: [<br>        {f1:'value11', f2:'value12'},<br>        {f1:'value21', f2:'value22'}<br>    ]<br>}); null
loadMsg string The message displayed when loading data from a remote site. Processing, please wait …
pagination boolean When set to true, it will display a pagination toolbar at the bottom of the DataGrid. false
rownumbers boolean When set to true, it will display a column with row numbers. false
singleSelect boolean When set to true, it will only allow selecting one row. false
checkOnSelect boolean If set to true, clicking a row will select/deselect the checkbox. If set to false, the checkbox will only be selected/deselected when the checkbox is clicked. Available since version 1.3. true
selectOnCheck boolean If set to true, clicking the checkbox will select the row. If set to false, selecting the row will not select the checkbox. Available since version 1.3. true
pagePosition string Defines the position of the pagination bar. Available values are: 'top', 'bottom', 'both'. Available since version 1.3. bottom
pageNumber number The initial page number when the pagination property is set. 1
pageSize number The initial page size when the pagination property is set. 10
pageList array The initial page size selection list when the pagination property is set. [10,20,30,40,50]
queryParams object Extra parameters sent when requesting remote data. <br>Example code: $('#dg').datagrid({<br>    queryParams: {<br>        name: 'easyui',<br>        subject: 'datagrid'<br>    }<br>}); {}
sortName string The column that can be sorted. null
sortOrder string The sort order for the column, can only be 'asc' or 'desc'. asc
multiSort boolean Defines if multiple columns sorting is enabled. Available since version 1.3.4. false
remoteSort boolean Defines if sorting data is done on the server. true
showHeader boolean Defines if the row header is displayed. true
showFooter boolean Defines if the row footer is displayed. false
scrollbarSize number The width of the scrollbar (when the scrollbar is vertical) or the height of the scrollbar (when the scrollbar is horizontal). 18
rowStyler function Returns a style string such as 'background:red'. The function requires two parameters: <br>rowIndex: The index of the row, starting from 0. <br>rowData: The corresponding record of the row. <br> <br>Code Example: $('#dg').datagrid({<br>    rowStyler: function(index,row){<br>        if (row.listprice>80){<br>            return 'background-color:#6293BB;color:#fff;'; // return inline style<br>            // the function can return predefined css class and inline style<br>            // return {class:'r1', style:{'color:#fff'}};    <br>        }<br>    }<br>});
loader function Defines how to load data from a remote server. Returns false to cancel the action. The function has the following parameters: <br>param: The parameter object to be passed to the remote server. <br>success(data): The callback function to be called when data retrieval is successful. <br>error(): The callback function to be called when data retrieval fails. <br> json loader
loadFilter function Returns the filtered data to be displayed. The function has one parameter 'data', which represents the original data. You can transform the original data into a standard data format. The function must return a standard data object containing 'total' and 'rows' properties. <br>Code Example: // removing 'd' object from asp.net web service json output<br>$('#dg').datagrid({<br>    loadFilter: function(data){<br>        if (data.d){<br>            return data.d;<br>        } else {<br>            return data;<br>        }<br>    }<br>});
editors object Defines the editors for editing rows. predefined editors
view object Defines the view of the datagrid. default view

Column Properties

The columns of the DataGrid are an array object, where each element is also an array. The elements of the array are configuration objects that define the fields of each column.

Code Example:

columns:[[
    {field:'itemid',title:'Item ID',rowspan:2,width:80,sortable:true},
    {field:'productid',title:'Product ID',rowspan:2,width:80,sortable:true},
    {title:'Item Details',colspan:4}
],[
    {field:'listprice',title:'List Price',width:80,align:'right',sortable:true},
    {field:'unitcost',title:'Unit Cost',width:80,align:'right',sortable:true},
    {field:'attr1',title:'Attribute',width:100},
    {field:'status',title:'Status',width:60}
]]
Name Type Description Default Value
title string The title text of the column. undefined
field string The field name of the column. undefined
width number The width of the column. If not defined, the width will auto-expand to fit its content. Not defining the width can degrade performance. undefined
rowspan number Indicates how many rows a cell occupies. undefined
colspan number Indicates how many columns a cell occupies. undefined
align string Indicates how to align the data of the column, can be 'left', 'right', 'center'. undefined
halign string Indicates how to align the header of the column, possible values: 'left', 'right', 'center'. If not assigned, the header alignment will be the same as the data alignment defined by the 'align' attribute. This attribute is available since version 1.3.2. undefined
sortable boolean Set to true to allow the column to be sorted. undefined
order string The default sort order, can only be 'asc' or 'desc'. This attribute is available since version 1.3.2. undefined
resizable boolean Set to true to allow the column to be resized. undefined
fixed boolean Set to true to prevent resizing when 'fitColumns' is set to true. undefined
hidden boolean Set to true to hide the column. undefined
checkbox boolean Set to true to display a checkbox. The checkbox has a fixed width. undefined
formatter function The formatter function for the cell, it takes three parameters: <br>value: The field value. <br>rowData: The row record data. <br>rowIndex: The row index. <br> <br>Code Example: $('#dg').datagrid({<br>    columns:[[<br>        {field:'userId',title:'User', width:80,<br>            formatter: function(value,row,index){<br>                if (row.user){<br>                    return row.user.name;<br>                } else {<br>                    return value;<br>                }<br>            }<br>        }<br>    ]]<br>}); undefined
styler function The style function for the cell, it returns a style string to customize the cell style, such as 'background:red'. The function takes three parameters: <br>value: The field value. <br>rowData: The row record data. <br>rowIndex: The row index. <br> <br>Code Example: $('#dg').datagrid({<br>    columns:[[<br>        {field:'listprice',title:'List Price', width:80, align:'right',<br>            styler: function(value,row,index){<br>                if (value < 20){<br>                    return 'background-color:#ffee00;color:red;';<br>                    // the function can return predefined css class and inline style<br>                    // return {class:'c1',style:'color:red'}<br>                }<br>            }<br>        }<br>    ]]<br>}); undefined
sorter function The custom field sort function for local sorting, it takes two parameters: <br>a: The first field value. <br>b: The second field value. <br> <br>Code Example: $('#dg').datagrid({<br>    remoteSort: false,<br>    columns: [[<br>        {field:'date',title:'Date',width:80,sortable:true,align:'center', <br>            sorter:function(a,b){ <br>                a = a.split('/'); <br>                b = b.split('/'); <br>                if (a[2] == b[2]){ <br>                    if (a[0] == b[0]){ <br>                        return (a[1]>b[1]?1:-1); <br>                    } else { <br>                        return (a[0]>b[0]?1:-1); <br>                    } <br>                } else { <br>                    return (a[2]>b[2]?1:-1); <br>                } <br>            } <br>        }<br>    ]]<br>}); undefined
editor string,object Indicates the edit type. When it is a string, it specifies the edit type. When it is an object, it contains two properties: <br>type: The edit type, possible types: text, textarea, checkbox, numberbox, validatebox, datebox, combobox, combotree. <br>options: The editor options corresponding to the edit type. undefined

Editor

Override the default defaults by using $.fn.datagrid.defaults.editors.

Each editor has the following behaviors:

Name Parameters Description
init container, options Initializes the editor and returns the target object.
destroy target Destroys the editor if necessary.
getValue target Gets the value from the editor's text.
setValue target, value Sets the value to the editor.
resize target, width Resizes the editor if necessary.

For example, the text editor (text editor) is defined as follows:

$.extend($.fn.datagrid.defaults.editors, {
    text: {
        init: function(container, options){
            var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
            return input;
        },
        destroy: function(target){
            $(target).remove();
        },
        getValue: function(target){
            return $(target).val();
        },
        setValue: function(target, value){
            $(target).val(value);
        },
        resize: function(target, width){
            $(target)._outerWidth(width);
        }
    }
});

DataGrid View

Override the default defaults by $.fn.datagrid.defaults.view.

The view is an object that tells the datagrid how to render rows. The object must define the following functions:

Name Parameters Description
render target, container, frozen Called when data is loaded. <br>target: DOM object, the datagrid object. <br>container: the row container. <br>frozen: indicates whether to render the frozen container.
renderFooter target, container, frozen This is an optional function to render the row footer.
renderRow target, fields, frozen, rowIndex, rowData This is an optional function that will be called by the render function.
refreshRow target, rowIndex Defines how to refresh the specified row.
onBeforeRender target, rows Triggered before the view is rendered.
onAfterRender target Triggered after the view is rendered.

Events

This event extends from the panel, and the following are the events added for the datagrid.

Name Parameters Description
onLoadSuccess data Triggered when data is loaded successfully.
onLoadError none Triggered when some error occurs while loading remote data.
onBeforeLoad param Triggered before sending a request to load data, if false is returned the load action will be canceled.
onClickRow rowIndex, rowData Triggered when a user clicks a row, parameters include: <br>rowIndex: the index of the clicked row, starting from 0 <br>rowData: the record corresponding to the clicked row
onDblClickRow rowIndex, rowData Triggered when a user double-clicks a row, parameters include: <br>rowIndex: the index of the double-clicked row, starting from 0 <br>rowData: the record corresponding to the double-clicked row
onClickCell rowIndex, field, value Triggered when a user clicks a cell.
onDblClickCell rowIndex, field, value Triggered when a user double-clicks a cell. <br>Code example: // when double-clicking a cell, begin editing and make the editor get focus<br>$('#dg').datagrid({<br> onDblClickCell: function(index,field,value){<br> $(this).datagrid('beginEdit', index);<br> var ed = $(this).datagrid('getEditor', {index:index,field:field});<br> $(ed.target).focus();<br> }<br>});
onSortColumn sort, order Triggered when a user sorts a column, parameters include: <br>sort: the field name of the sorted column <br>order: the order of the sorted column
onResizeColumn field, width Triggered when a user resizes a column.
onSelect rowIndex, rowData Triggered when a user selects a row, parameters include: <br>rowIndex: the index of the selected row, starting from 0 <br>rowData: the record corresponding to the selected row
onUnselect rowIndex, rowData Triggered when a user unselects a row, parameters include: <br>rowIndex: the index of the unselected row, starting from 0 <br>rowData: the record corresponding to the unselected row
onSelectAll rows Triggered when a user selects all rows.
onUnselectAll rows Triggered when a user unselects all rows.
onCheck rowIndex,rowData Triggered when a user checks a row, parameters include: <br>rowIndex: the index of the checked row, starting from 0 <br>rowData: the record corresponding to the checked row <br>This event is available since version 1.3.
onUncheck rowIndex,rowData Triggered when a user unchecks a row, parameters include: <br>rowIndex: the index of the unchecked row, starting from 0 <br>rowData: the record corresponding to the unchecked row <br>This event is available since version 1.3.
onCheckAll rows Triggered when a user checks all rows. This event is available since version 1.3.
onUncheckAll rows Triggered when a user unchecks all rows. This event is available since version 1.3.
onBeforeEdit rowIndex, rowData Triggered when a user starts editing a row, parameters include: <br>rowIndex: the index of the edited row, starting from 0 <br>rowData: the record corresponding to the edited row
onAfterEdit rowIndex, rowData, changes Triggered when a user completes editing a row, parameters include: <br>rowIndex: the index of the edited row, starting from 0 <br>rowData: the record corresponding to the edited row <br>changes: the changed field/value pairs
onCancelEdit rowIndex, rowData Triggered when a user cancels editing a row, parameters include: <br>rowIndex: the index of the edited row, starting from 0 <br>rowData: the record corresponding to the edited row
onHeaderContextMenu e, field Triggered when the header of the datagrid is right-clicked.
onRowContextMenu e, rowIndex, rowData Triggered when a row is right-clicked.

Methods

Name Parameters Description
options none Returns the options object.
getPager none Returns the pager object.
getPanel none Returns the panel object.
getColumnFields frozen Returns the column fields, if frozen is set to true, the frozen column fields are returned. <br>Code example: var opts = $('#dg').datagrid('getColumnFields'); // get unfrozen columns<br>var opts = $('#dg').datagrid('getColumnFields', true); // get frozen columns
getColumnOption field Returns the options for the specified column.
resize param Adjusts the size and layout.
load param Loads and displays the first page of rows, if the 'param' parameter is specified, it will replace the queryParams property. Typically, this method is called to load new data from the server by passing some parameters from the query. $('#dg').datagrid('load',{<br> code: '01',<br> name: 'name01'<br>});
reload param Reloads the rows, like the load method, but stays on the current page.
reloadFooter footer Reloads the footer rows. Code example: // update footer row values and then refresh<br>var rows = $('#dg').datagrid('getFooterRows');<br>rows[0]['name'] = 'new name';<br>rows[0]['salary'] = 60000;<br>$('#dg').datagrid('reloadFooter');<br>// update footer rows with new data<br>$('#dg').datagrid('reloadFooter',[<br> {name: 'name1', salary: 60000},<br> {name: 'name2', salary: 65000}<br>]);
loading none Displays the loading status.
loaded none Hides the loading status.
fitColumns none Makes the columns auto expand/collapse to fit the datagrid width.
fixColumnSize field Fixes the column size. If the 'field' parameter is not set, all columns' sizes will be fixed. <br>Code example: $('#dg').datagrid('fixColumnSize', 'name'); // fix the 'name' column size<br>$('#dg').datagrid('fixColumnSize'); // fix all columns size
fixRowHeight index Fixes the height of the specified row. If the 'index' parameter is not set, all rows' heights will be fixed.
freezeRow index Freezes the specified row so that these frozen rows are always displayed on the top when the datagrid scrolls down. This method is available since version 1.3.2.
autoSizeColumn field Adjusts the column width to fit the content. This method is available since version 1.3.
loadData data Loads local data, the old rows are removed.
getData none Returns the loaded data.
getRows none Returns the current page rows.
getFooterRows none Returns the footer rows.
getRowIndex row Returns the index of the specified row, where the row parameter can be a row record or the value of an id field.
getChecked none Returns all rows checked by the checkbox. This method is available since version 1.3.
getSelected none Returns the first selected row or null.
getSelections none Returns all selected rows; it returns an empty array if no records are selected.
clearSelections none Clears all selections.
clearChecked none Clears all checked rows. This method is available since version 1.3.2.
scrollTo index Scrolls to the specified row. This method is available since version 1.3.3.
highlightRow index Highlights a row. This method is available since version 1.3.3.
selectAll none Selects all rows on the current page.
unselectAll none Deselects all rows on the current page.
selectRow index Selects a row, with row index starting from 0.
selectRecord idValue Selects a row by passing the id value as a parameter.
unselectRow index Deselects a row.
checkAll none Checks all rows on the current page. This method is available since version 1.3.
uncheckAll none Unchecks all rows on the current page. This method is available since version 1.3.
checkRow index Checks a row, with row index starting from 0. This method is available since version 1.3.
uncheckRow index Unchecks a row, with row index starting from 0. This method is available since version 1.3.
beginEdit index Begins editing a row.
endEdit index Ends editing a row.
cancelEdit index Cancels editing a row.
getEditors index Gets the editors for the specified row. Each editor has the following properties: actions, target, field, type.
getEditor options Gets the specified editor, where options include index and field.
refreshRow index Refreshes a row.
validateRow index Validates the specified row and returns true if valid.
updateRow param Updates the specified row, where param includes index and row.
appendRow row Appends a new row. The new row is added at the last position.
insertRow param Inserts a new row, where param includes index and row.
deleteRow index Deletes a row.
getChanges type Gets the rows changed since the last commit. Type can be inserted, deleted, updated, etc.
acceptChanges none Commits all changes since the data was loaded or since the last call to acceptChanges.
rejectChanges none Rolls back all changes since the data was created or since the last call to acceptChanges.
mergeCells options Merges cells into one cell, where options include index, field, rowspan, and colspan.
showColumn field Shows the specified column.
hideColumn field Hides the specified column.
❮ Plugins Dt Tree Jeasyui Tree Tree6 ❯