jTable is used to develop AJAX based CRUD (Create/Retrive/Update/Delete) tables without coding HTML and JavaScript. Only needed HTML tag is a simple div element in your page:
<div id="MyTableContainer"></div>
To initialize a jTable instance, you can call jtable method in the ready event of the document as like that:
<script type="text/javascript">
$(document).ready(function () {
$('#MyTableContainer').jtable({
//General options comes here
actions: {
//Action definitions comes here
},
fields: {
//Field definitions comes here
}
});
});
</script>
jTable has three types of options:
NOTE: When you create a jTable instance, a table is created but no data is loaded to the table. load method is used to do it.
A jQuery object that can be used instead of the '+ add new record' link. Thus you can set any element on the page to open the 'add new record' dialog.
A boolean value indicates that whether jTable shows animations when user creates, updates or deletes a row.
A boolean value indicates that whether jTable allows user to resize data columns by dragging.
A boolean value indicates that whether jTable allows user to show/hide data columns by right clicking table header.
Default format of a date field. See jQueryUI datepicker formats.
Default sorting of table. It can be a field name of a column of the table. For instance, if you want table sorted by Name by default, defaultSorting can be 'Name ASC' or 'Name DESC'.
This option can be a boolean value or a function. If it is a boolean value, that indicates whether a confirmation dialog is shown when user clicks delete button/icon for a record.
If this option is a function, It can fully control delete confirmation process. It must be a function as shown below.
deleteConfirmation: function(data) {
//...
}
data argument has some properties to control confirmation process:
For example, if you want to show some additional information to user on delete confirmation, you can write a function like that:
deleteConfirmation: function(data) {
data.deleteConfirmMessage = 'Are you sure to delete person ' + data.record.Name + '?';
}
jQueryUI effect to be used while opening a jQueryUI dialog. Some options are 'blind', 'bounce', 'clip', 'drop', 'explode', 'fold', 'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide'... etc. See jQueryUI documentation for all options.
jQueryUI effect to be used while closing a jQueryUI dialog. Some options are 'blind', 'bounce', 'clip', 'drop', 'explode', 'fold', 'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide'... etc. See jQueryUI documentation for all options.
Indicates that whether jTable allows user to select multiple rows at once.
If this options is set to true, jTable automatically closes other open child tables when a child table is opened (accordion style).
Indicates that whether jTable uses paging or not.
If paging enabled, this value indicates number of rows in a page.
Indicates that whether jTable saves/loads user preferences such as resized columns. Saving/restoring preferences are based on a hashed value that is generated using tableId, all column names and total column count. So, changing columns will change the hash and user preferences are reset.
Indicates that whether jTable allows user to select rows on the table.
Indicates that whether jTable shows checkbox column for selecting.
Indicates that whether jTable allows user to select a row by clicking anywhere on the row. This can be set as false to allow user selecting a row only by clicking to the checkbox (see selectingCheckboxes option).
Indicates that whether jTable will show a close button/icon for the table. When user clicks the close button, closeRequested event is raised. This option is used internally by jTable to close child tables.
Indicates that whether jTable will sort the table or not.
A string that is a unique identifier for this table. This value is used on saving/restoring user preferences and it's optional.
A string that is shown on top of the table. This is optional, if you don't supply the title option, title area is not displayed at all.
A field definition defines structure and behavior of a field of the record. It's generally formatted as:
FieldName: {
//Field options
}
A boolean value that indicates whether this column can be resized by user. Table's columnResizable option must be set to true (it's default) to use this option.
A boolean value that indicates whether this field is shown in the create record form.
A boolean value that indicates whether this field is shown in the edit record form.
You can set a default value for a field. It must be a valid value. For instance, if the field is an option list, it must be one of these options.
This option is a function that allows you to define a fully custom column for table. jTable directly shows return value of this function on the table. See the sample below:
TestColumn: {
title: 'Test',
display: function (data) {
return '<b>test</b>';
}
}
This sample Test column returns a bold 'test' string for all rows. You can return any text, html code or jQuery object that will be shown on the table. This method is called for each row. You can get record of the row using data.record. So, if your record has Name property, you can use data.record.Name property to get the Name.
display function can be used for many purposes such as creating calculated columns, opening child tables for a row... etc. See demos for detailed usage.
This option is a function that allows you to define a fully custom input element for create and edit forms. jTable directly shows return value of this function on the form. See the sample below:
Name: {
title: 'Name',
width: '20%',
input: function (data) {
if (data.record) {
return '<input type="text" style="width:200px" value="' + data.record.Name + '" />';
} else {
return '<input type="text" style="width:200px" value="enter your name here" />';
}
}
}
Here, we return a simple text input for Name field of the record. If this input is being created for edit form, you can get editing record using data.record property. If this input is being created for create form, it is undefined. You can also use data.value to get current value of the field. This is default value (if defined) of field for create form, current value of field for edit form.
While jTable automatically created appropriate input element for each field, you can use input option to create custom input elements.
A string value that can be set as the class of an input item for this field in create/edit forms. So you can style input elements in the forms for this field. This can be useful when working with validation plug-ins (we will see soon).
A boolean value that indicates whether this field is the key field of the record. Every record must has one and only one key field that is used as key on update and delete operations.
A boolean value that indicates whether this field is shown in the table.
A string value that can be set as class/classes of a cell of this field (td element) in the table. Thus, you can stylize fields in the table.
If this field's value will be selected in an option list (combobox as default, can be radio button list), you must supply a source. An option source can be one of these values:
Indicates that whether this column will be used to sort the table (If table is sortable).
Column header in the table and label in the forms for this field. This option is required if the field is shown on the table or create/edit forms.
Data type for this field. If field is text or number, no need to set type. Other types are:
A column (related to a field) can be showed or hided by user or this option. Values can be:
Note: User can open column selection list by right clicking the table header if columnSelectable option is true (it's true as default).
Width of the column for this field in the table. Can be any CSS unit ('15%', '120px'... so on). It's required if the field is shown on the table.
An action defines an URL to perform AJAX call to server. There are four types of action:
An action must be defined in actions list of jTable options a like:
...
actions: {
//Actions definitions come here
}
...
When you use the load method, jTable makes an AJAX POST call to this URL address to get list of records. This URL must return a JSON object. Here, there is a sample return value for this URL:
{
"Result":"OK",
"Records":[
{"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
{"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
]
}
Result property can be "OK" or "ERROR". If it is "OK", Records property must be an array of records. If Result is "ERROR", Message property must explain reason of the error to show to the user.
Spesifically, a date field (that is transferred between jTable and server side code) must be one of the formats below:
If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX call:
Also, one additional information is expected from server:
If sorting is enabled, jTable sends one additional query string parameter to the server on listAction AJAX call:
When you create and save a record, jTable makes an AJAX POST call to this URL address to save the record to the server.
createAction is optional. If it is not defined, user can not add new records to the table. This URL must return a JSON object. Here, there is a sample return value for this URL:
{
"Result":"OK",
"Record":{"PersonId":5,"Name":"Dan Brown","Age":55,"RecordDate":"\/Date(1320262185197)\/"}
}
Result property can be "OK" or "ERROR". If it is "OK", Record property must be the newly created record. This is needed by jTable to add record to the table. If Result is "ERROR", Message property must explain reason of the error to show to the user.
When you edit and save a record, jTable makes an AJAX POST call to this URL address to update record on the server.
updateAction is optional. If it is not defined, edit image (button) is not shown. This URL must return a JSON object. Here, there is a sample return value for this URL:
{"Result":"OK"}
Result property can be "OK" or "ERROR". If Result is "ERROR", Message property must explain reason of the error to show to the user.
When you delete a record, jTable makes an AJAX POST call to this URL address to delete the record on the server.
deleteAction is optional. If it is not defined, delete image (button) is not shown. This URL must return a JSON object. Here, there is a sample return value for this URL:
{"Result":"OK"}
Result property can be "OK" or "ERROR". If Result is "ERROR", Message property must explain reason of the error to show to the user.
This method is used to add a new record to the table programmatically. Parameters are:
Here, the simplest usage of addRecord method:
$('#StudentTableContainer').jtable('addRecord', {
record: {
Name: 'Halil ibrahim Kalkan',
EmailAddress: 'halil@jtable.org',
Password: '123',
Gender: 'M',
CityId: 4,
BirthDate: '2002-11-18',
Education: '2',
About: 'adding test record',
IsActive: true,
RecordDate: '2011-11-12'
}
});
This method is used to close an open child row for a table row. See openChildRow method. (This method is internally used by jTable to close child tables.)
This method is used to close an open child table for a table row. row is a jQuery row object on the table. closed is a callback function that is called when child table is closed. See openChildTable method.
This method is used to change visibility property of a column. Values can be fixed (column is shown always), visible (column is shown as default) and hidden (column is hidden as default). See field visibility option.
This method is used to delete an existing record from the table programmatically. Parameters are:
Here, the simplest usage of deleteRecord method:
$('#StudentTableContainer').jtable('deleteRecord', {
key: 42
});
Deletes given rows from server and table. rows parameter must be a jQuery selection. This method can be combined with selectedRows method. Thus, you can get selected rows and pass to deleteRows method to delete them.
Compeletely removes table from it's container.
This method is used to get child row for a table row. Thus, you can add content to the child row. See openChildRow method.
This method returns true if child row is open for specified row. See openChildRow method.
Loads records from the server. All parameters are optional. If you want to pass some parameters to the server, you can pass them in the postData parameter while calling the load method, like this:
$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });
You can get people who are living in city 2 and whose name is Halil like shown above. Surely, you must handle these parameters in the server side. Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.
This method is used to open child row for a table row. Child rows generally used to show child tables. If you want to show child tables, you don't need to use this method, use openChildTable method instead. If you want to open a custom child row, use this method. It returns the opened child row. Thus, you can fill it with a custom content. A child row is related to a specific data row in the table (which is passed as row agrument). If the data row is removed from table, it's child is also automatically removed.
This method is used to create and open a child table for a data row (See demos page). row argument is a data row on the table, tableOptions are standard jTable options that is used to initialize child table. opened is a callback that is called by jTable when the child table is shown (After opening animation is finished).
Re-loads records from server with last postData. This method can be used to refresh table data from server since it does not change current page, sorting and uses last postData (on load call). Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.
Gets all selected rows on the table as jQuery selection. See the sample below:
var $selectedRows = $('#PersonTable').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var personId = record.PersonId;
var name = record.Name;
});
Here, we get all selected rows, then iterate over rows and get the record related to the row, then get some fields of the record (See demos for more).
Can be used to programmatically open a 'create new record' form dialog.
This method is used to update an existing record on the table programmatically. Parameters are:
Here, the simplest usage of updateRecord method:
$('#StudentTableContainer').jtable('updateRecord', {
record: {
StudentId: 42,
Name: 'Halil Kalkan',
EmailAddress: 'halil@jtable.org',
Password: '123456',
Gender: 'M',
CityId: 4,
BirthDate: '2001-11-18',
Education: '3',
About: 'updated this record',
IsActive: true,
RecordDate: '2012-01-05'
}
});
This event is raised when user clicks close button/icon of the table. Close button is shown if showCloseButton is set to true. This event has no argument.
This event is raised when an edit or create form dialog is closed. You can reach the form using the data.form argument. You can get the type of the form using data.formType argument. It can be 'edit' or 'create'.
This event is raised when an edit or create form is created for a record. You can reach the form using the data.form argument. You can get type of the form using the data.formType argument. It can be 'edit' or 'create'. If formType is edit, you can reach the editing record using the data.record argument (for example, you can get the name of the editing person as data.record.Name).
This event is raised when save/submit button is clicked for a create or edit form. You can reach the form using the data.form argument. You can get type of the form using the data.formType argument. It can be 'edit' or 'create'. You can validate the form on this event. If you return false from this event callback, submit operation is cancelled.
This event is raised just before AJAX request to load records from server. It has no arguments.
This event is raised when user successfully creates and saves a new record. You can get the added record using data.record argument. You can get the response JSON object returned from server as data.serverResponse.
This event is raised when user successfully deletes a record. You can get the deleted record using data.record argument. You can get the deleted table row by data.row argument. You can get the response JSON object returned from server as data.serverResponse.
This event is raised when jTable loads records from server and refreshes the table (If paging enabled, this event is also raised when user changes the current page). You can get all records loaded from server by data.records argument. You can get the response JSON object returned from server as data.serverResponse.
This event is raised when user successfully updates a record. You can get the updated record using data.record argument. You can get the updated table row by data.row argument. You can get the response JSON object returned from server as data.serverResponse.
This event is raised when a row is inserted to the shown table. A new row can be inserted either when user added a new record or records loaded from server. When records loaded from server, rowInserted event is called for each row. So, you can modify row or do whatever you need. You can get the row using data.row, you can get related record with data.record. Finally, if this is a new record (that's added by user) data.isNewRow is set to true by jTable.
This event is raised when either user deletes row/rows (actual record deletion from server) or during re-loading records from server (all rows cleared but not deleted from server). You can get all removed rows by data.rows as jQuery selection. You can get remove reason by data.reason (can be 'deleted' or 'reloading').
This event is raised when a row updated. A row is updated when user updates a record. You can get the updated row using data.row, you can get related record with data.record. This event is raised after recordUpdated.
This event is raised when selected rows on the table changes in anyway. It may change when user selects/deselects a row, a selected row is deleted, page changed while some rows are selected... etc. You can get selected rows by selectedRows method.
jTable can be easily localized. You can use the messages option to localize a jTable instance on initialization. Default value of the messages option is shown below:
messages: {
serverCommunicationError: 'An error occured while communicating to the server.',
loadingMessage: 'Loading records...',
noDataAvailable: 'No data available!',
addNewRecord: '+ Add new record',
editRecord: 'Edit Record',
areYouSure: 'Are you sure?',
deleteConfirmation: 'This record will be deleted. Are you sure?',
save: 'Save',
saving: 'Saving',
cancel: 'Cancel',
deleteText: 'Delete',
deleting: 'Deleting',
error: 'Error',
close: 'Close',
cannotLoadOptionsFor: 'Can not load options for field {0}',
pagingInfo: 'Showing {0} to {1} of {2} records',
canNotDeletedRecords: 'Can not deleted {0} of {1} records!',
deleteProggress: 'Deleted {0} of {1} records, processing...'
}
Here, a sample localization for Turkish language:
//Localization
var turkishMessages = {
serverCommunicationError: 'Sunucu ile iletişim kurulurken bir hata oluştu.',
loadingMessage: 'Kayıtlar yükleniyor...',
noDataAvailable: 'Hiç kayıt bulunmamaktadır!',
addNewRecord: '+ Yeni kayıt ekle',
editRecord: 'Kayıt düzenle',
areYouSure: 'Emin misiniz?',
deleteConfirmation: 'Bu kayıt silinecektir. Emin misiniz?',
save: 'Kaydet',
saving: 'Kaydediyor',
cancel: 'İptal',
deleteText: 'Sil',
deleting: 'Siliyor',
error: 'Hata',
close: 'Kapat',
cannotLoadOptionsFor: '{0} alanı için seçenekler yüklenemedi!',
pagingInfo: 'Toplam {2}, {0} ile {1} arası gösteriliyor',
canNotDeletedRecords: '{1} kayıttan {0} adedi silinemedi!',
deleteProggress: '{1} kayıttan {0} adedi silindi, devam ediliyor...'
};
//Prepare jtable plugin
$('#PersonTable').jtable({
messages: turkishMessages, //Localization
//...
actions: {
//...
},
fields: {
//...
}
});