FathGrid

JavaScript frontend data table/grid with paging, sorting, filtering, grouping, sub-grids, exporting and editing. Can be used with any framework.

30
7
JavaScript

FathGrid

No dependencies pure JavaScript data table/grid with:

  • instant search,
  • paging,
  • sorting (by multiple columns),
  • filtering (with text input or selecting from a list),
  • printing,
  • export to txt, csv, pdf, xls, etc.,
  • multiple rows selection,
  • custom row highlights,
  • show/hide columns,
  • columns resizing,
  • grouping and data aggregation (with group header/footer),
  • in-place data edit mode,
  • inline data, JSON fetching or server-side processing,
  • sub-grid,
  • interactive data graph.

Sample screenshot
Sample screenshot

Just include .js file in your HTML and initialize table with:

var t1=FathGrid("table1",{});

where “table1” is an ID of HTML table.

<table id="table1">
...
</table>

Online demos

Demo 1 | Demo 2 | Editing | Forms Demo |

Table Data

Table data can be set inline, in your HTML, or dynamically loaded with setData method or configuration option.

Inline Data

Simply add all your data in table body. FathGrid will load all content and show only first page.
Sample:

<table id="table1">
    <thead>
        <tr><th>id</th><th>name</th></tr>
    </thead>
    <tbody>
        <tr><td>1</td><td>first row</td></tr>
        <tr><td>2</td><td>second row</td></tr>
        <tr><td>3</td><td>third row</td></tr>
    </tbody>
</table>

Dynamic data

Table content can be empty and data loaded from JavaScript array using setData method:

<table id="table1">
    <thead>
        <tr><th>id</th><th>name</th></tr>
    </thead>
    <tbody>
    </tbody>
</table>
<script>
  var t1=FathGrid('table1',{data:[
    ['1','first row'],
    ['2','second row'],
    ['3','third row']
    ]
  });
  //or, calling a method
  t1.setData([['10','...'],['22','...'],['30','...']]);
</script>

JSON data objects

Table content can be set using array of JSON objects. In that case, columns definition must include “name” property which specifies object attribute name to display:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => {
    var t1=FathGrid("table1",{
      columns:[
          {editable:false, name:'id'},
          {
            name:'userId', 
            filter:users,
            listOfValues:users,
            value:function(item){return users.find(i=>i.value==item.userId).name;}
          },
          {name:'title'},
          {
            name:'body',
            html:function(item){return `<b>${item.body}</b>`}
          },
      ],
      data:json,
    });
  })

Server-side data

For huge data amounts, use server-side processing (sorting, paginating and filtering) with serverURL configuration option:

t1=FathGrid("table1",{
  serverURL:'https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${size}&_sort=${sort}&_order=${order}&q=${search}&${filters}',
  ...
});

Configuration options

NameDescriptionDefault
sizepage size20
pagepage number to show1
filterableshow filter row in theadtrue
editableallow editstrue
pageableallow paginationtrue
printableallow printingtrue
exportableallow data exporttrue
resizableallow column resizingtrue
restoreColumnsautomatically restore column widths from previous user session with the same tablefalse
sortableAllow sorting. Click on column header to sort, hold shift to add column to multisort.true
multiselectAllow selecting multiple rows. Adds select checkbox to the rows. Use getSelectedItems API to get selected data items.false
showGraphshow graph tool in the toolbartrue
showGroupingshow grouping and aggregation tool in the toolbartrue
selectColumnsshow columns list in the toolbartrue
showFooteradd footer row to tablefalse
showGroupFooteradd footer row after each group of recordsfalse
showGroupHeaderadd header row before each group of recordstrue
showGroupRowsdisplay/hide data rows between group header and group footertrue
showTableTotaladd footer row at the end of a table with data aggregation valuesfalse
datatable datadata from HTML table content
rowClassfunction to return a string with row classes. Use it to change row appearance based on some criteria.function(data,index){}
onChangefunction to call when cell data is changedfunction(data, col, old_value, new_value){}
groupOnfunction which returns a HTML string to group records on
Eg:

//group on first column

sortBy : [1],

//grouping expression

groupOn : item=>`${item[0]}`,

//show aggregate footer

showGroupFooter : true,

{}
sortByArray or column indices to sort always. Usable for grouping records.{}
columnsconfigure columns{}
serverURLtemplated string URL for data retrievalundefined
prepareDatacustom function which converts received JSON object into data arrayasync function(json)
rtlset to true for RTL languagesfalse
templateTemplated HTML string for grid wrapper element. Use this to insert custom HTML between grid elements.{tools}{info}{graph}{table}{pager}
graphTypegraph type, line, bar, pie, etcline
graphValuesfunction which returns an object to initialize data graph{title: 'Graph Title', labels: ['Jan','Feb','Mar',...], values: [100,200,300,...]}
onInitFilterfunction called after filter row is initialized. Function parameter is TR element of table filter.function(Element){}
onInitTablefunction called after table data is refreshed. Function paramter is TBODY element which contains data rows.function(Element){}
onInitInputfunction called after table cell editor is initialized. Function paramters are:
- item : data item
- idx : column index
- el : TD cell element in which input is located
function(Item, Idx, El){}
langlanguage translation object {
of:"of",
yes:"yes",
export:"Export",
previous:"Previous",
next:"Next",
last:"Last",
first:"First",
gotoPage:"Goto Page",
loading:'Loading...',
selectRow:'Select Row',
showSelectedOnly:'Show Only Selected Rows',
groupby:'Group By',
avg:'Avg',
count:'Count',
min:'Min',
max:'Max',
sum:'Sum',
show_grouping_controls:'Show Grouping Controls',
show_graph:'Show Graph',
select_columns:'Select Columns',
type:'Type',
none:'None',
line:'Line',
bar:'Bar',
pie:'Pie',
}

Columns

Columns definition is an array of objects defining column appereance and functions.

NameDescriptionDefault
namefield name in data record
visibleboolean. if set to false, column is not visible
filterlist of values for filter select, or a null to automatically build the list from table data
valuefunction which returns cell text contentfunction(item){}
htmlfunction which returns cell HTML contentfunction(item){}
headerheader text
footerfunction which returns footer cell HTML contentfunction(data,element){}
groupFooterfunction which returns group footer cell HTML content. Pre-defined values that can be used are:
- FathGrid.SUM
- FathGrid.AVG
- FathGrid.MIN
- FathGrid.MAX
- FathGrid.COUNT
- FathGrid.FIRST
- FathGrid.LAST
function(data,element){}
editableboolean if edit is allowed, or a function(item,col) which returns boolean
typeinput type for cell editor. supported values are: text, color, image, date, email, number, checkbox, textarea.
patternregular expression to check the input value against when editing cell content
titlehelp string for input in edit mode
widthcolumn width. if value is number, in pixel units, or set velue to string with custom units (eg. '10rem').auto
printableinclude this column in printtrue
listOfValuesarray of selectable values when editing
classstring of CSS classes to add to column cells. Eg. 'text-right text-bold'
filterInputClassstring of CSS classes to add to column filter input. Eg. 'form-control text-right text-bold'

To add filter values to column 5, and let grid fill in values for filter of column 3, use:

var t1=FathGrid("table1",{
  size:10,
  editable:true,
  filterable:true,
  sortable:true,
  columns:[
    {editable:false, header:'ID#'},
    {
      listOfValues:[1,2,3,4,5,"Abel","SomeName"], //list of values for edit, or a function(data,col) which returns list of values
    },
    {
      filter:null, //array or null for auto-generation of filter list
      editable:function(data,col){return data.rownum>3}, //is field editable
    },
    {
      type:'text', //edit input type: text, date, email, checkbox, textarea
      pattern:'[0-9]*',
      title:'only numbers, please!'
    },
    {type:'checkbox',
      editable:true,
      filter:[{name:'no',value:0},{name:'yes',value:1}],
      footer: FathGrid.SUM, //display sum of field "amount"

    },
  ],
});

Export

Text, CSV, HTML and XLS export formats are supported.

To enable PDF export, include jsPDF.js in your page and PDF export functionality will be automatically enabled.

API

.getData() // returns table data

.setData(newData) // sets new table data, possibly after delete or creating a new record

.exportData(format, filename) //export data

.render() //redraw

.sort(column_index [, asc|desc][, multisort] ) //sort data, set multisort to sort by multiple columns

.getSort() //returns array of 1-based column indices, negative if using descending sort order

.setSort(indices) // eg. .setSort([2,1]) to sort by second then first column

.filter(column_index, query) //add filter string to a column

.getFilter() //returns array of column query strings

.editCell(rownum, col) //start editor in the cell

.search([query string]) //instant search in all columns. Calling this method without argument returns current search string.

.getSelectedItem() //return data item of selected row or null if no row is selected

.deleteRow(rownum) //deletes row specified by rownum parameter (1 = first row, 2= second row, …)

.insertRow(rownum, item) //inserts new item into row number specified by rownum parameter (1=first row)

.selectRow(rownum)

.restoreColumns() //restores column widths from local storage of previous session on this table

.saveConfig()

.loadConfig(objConfig)

.destroy()

License

MIT