jQuery editTable v0.2.0
jQuery editTable is a very small jQuery Plugin (~1Kb gzipped) that fill the gap left by the missing of a default input field for data tables. jQuery editTable can be used both in ajax and/or HTTP POST contest and let you preset the title and number of columns or just let complete freedom to the user. You can even append custom behaviors to single column cells (ex. jQuery UI Datepicker). The only limit is your imagination! :)
Download it on GitHub
To use it you just have to include jQuery and a copy of the plugin in your head or footer:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.edittable.min.js"></script>
<link rel="stylesheet" href="jquery.edittable.min.css">
Now you can trigger editTable on any textarea or block element (ex. div, article, section ...). In case you trigger it on a textarea, its content will be used as JSON source for the table. If the textarea is inside a form, on submit, its content will be updated with the new JSON data. Otherwise, if you trigger it on a block element the table will be appended to the element itself (ajax).
var mytable = $('#edittable').editTable({
data: [['']], // Fill the table with a js array (this is overridden by the textarea content if not empty)
tableClass: 'inputtable', // Table class, for styling
jsonData: false, // Fill the table with json data (this will override data property)
headerCols: false, // Fix columns number and names (array of column names)
maxRows: 999, // Max number of rows which can be added
first_row: true, // First row should be highlighted?
row_template: false, // An array of column types set in field_templates
field_templates: false, // An array of custom field type objects
// Validate fields
validate_field: function (col_id, value, col_type, $element) {
return true;
}
});
There are of course many methods which can be used on the created table. Let's see...
mytable.loadData(dataArray); // Fill the table with js data
mytable.loadJsonData(jsonData); // Fill the table with JSON data
mytable.getData(); // Get a js array of the table data
mytable.getJsonData(); // Get JSON from the table data
mytable.reset(); // Reset the table to the initial set of data
mytable.isValidated() // Check if the table pass validation set with validate_field
To define a custom field type object (click here for a full example):
[
'checkbox' : {
html: '<input type="checkbox"/>', // Input type html
// How to get the value from the custom input
getValue: function (input) {
return $(input).is(':checked');
},
// How to set the value of the custom input
setValue: function (input, value) {
if ( value ){
return $(input).attr('checked', true);
}
return $(input).removeAttr('checked');
}
}
]
That's it, now give a look to the following examples to understand how it works.
Example 1 - Basics
In the first example we'll implement the simplest HTML POST use of editTable. If you are looking to use editTable on ajax contest instead just give a look to the next example.
INDEX.PHP
<form method="post" action="output.php">
<textarea id="source" style="display:none" name="myField" ><?php
echo json_encode(array(
array('Period','Full Board', 'Half Board', 'Bed & Breakfast'),
array('01/01 - 30/01','50.00 €', '40.00 €', '30.00 €'),
array('01/02 - 28/02','55.00 €', '45.00 €', '35.00 €'),
array('01/03 - 31/03','60.00 €', '50.00 €', '40.00 €'),
array('01/04 - 30/04','55.00 €', '45.00 €', '35.00 €'),
array('01/05 - 31/05','50.00 €', '40.00 €', '30.00 €')
));
?></textarea>
<button type="submit">Send data</button>
</form>
SCRIPT.JS
$(window).ready(function () {
$('#source').editTable();
});
OUTPUT.PHP
<?php var_dump( json_decode( stripslashes( $_POST['myField'] ) ) ); ?>
Example 2 - AJAX with editable columns:
Ajax load JSON
Reset Table
Show Code
index.htm
<div id="edittable"></div>
<a href="#" class="sendjson button">Send JSON (check your console)</a>
<a href="#" class="loadjson button">Load JSON from textarea</a>
<a href="#" class="reset button">Reset Table</a>
script.js
// Initialize table example 1
var eTable = $('#edittable').editTable({
data: [
["Click on the plus symbols on the top and right to add cols or rows"]
]
});
// Load json data trough an ajax call
$('.loadjson').click(function () {
var _this = $(this),text = $(this).text();
$(this).text('Loading...');
$.ajax({
url: 'output.php',
type: 'POST',
data: {
ajax: true
},
complete: function (result) {
_this.text(text);
eTable.loadJsonData(result.responseText);
}
});
return false;
});
// Reset table data
$('.reset').click(function () {
eTable.reset();
return false;
});
// Send JSON data trough an ajax call
$('.sendjson').click(function () {
$.ajax({
url: 'output.php',
type: 'POST',
data: {
ajax: true,
data: eTable.getJsonData()
},
complete: function (result) {
console.log(JSON.parse(result.responseText));
}
});
return false;
});
output.php
<?php
if ( isset( $_POST['ajax'] ) ){
header( 'Content-Type: application/json' );
if ( isset( $_REQUEST['data'] ) ){
$data = json_decode( stripslashes( $_REQUEST['data'] ) );
} else {
$data = array(
array('Carbon','Hydrogen','Nitrogen','Oxygen'),
array(10,15,1,0),
array(8,11,1,2),
array(10,15,1,1),
array(12,17,1,1),
array(14,19,1,2)
);
}
echo json_encode( $data );
die();
}
Example 3 - Fixed columns, Datepicker, Rows limit:
Show Code
index.htm
<div id="edittable2"></div>
script.js
// Initialize table example 3
$("#edittable2").editTable({
data: [
["01/01/2013","01/30/2013","50,00 €"],
["02/01/2013","02/28/2013","50,00 €"]
],
headerCols: [
'From',
'To',
'Price'
],
maxRows: 3
});
// Example of jQuery UI datePicker
$("#edittable2").on("focusin", "td:nth-child(1) input, td:nth-child(2) input", function(){
$(this).datepicker();
});
Example 4 - Custom field types & validation
script.js
/**
* Example 4 - Custom field types & validation
*/
var mynewtable = $('#examplex').editTable({
field_templates: {
'checkbox' : {
html: '<input type="checkbox"/>',
getValue: function (input) {
return $(input).is(':checked');
},
setValue: function (input, value) {
if ( value ){
return $(input).attr('checked', true);
}
return $(input).removeAttr('checked');
}
},
'textarea' : {
html: '<textarea/>',
getValue: function (input) {
return $(input).val();
},
setValue: function (input, value) {
return $(input).text(value);
}
},
'select' : {
html: '<select><option value="">None</option><option>All</option></select>',
getValue: function (input) {
return $(input).val();
},
setValue: function (input, value) {
var select = $(input);
select.find('option').filter(function() {
return $(this).val() == value;
}).attr('selected', true);
return select;
}
}
},
row_template: ['checkbox', 'text', 'text', 'textarea', 'select'],
headerCols: ['Yes/No','Date','Value','Description', 'Which?'],
first_row: false,
data: [
[false,"01/30/2013","50,00 €","Lorem ipsum...\n\nDonec in dui nisl. Nam ac libero eget magna iaculis faucibus eu non arcu. Proin sed diam ut nisl scelerisque fermentum."],
[true,"02/28/2013","50,00 €",'This is a <textarea>','All']
],
// Checkbox validation
validate_field: function (col_id, value, col_type, $element) {
if ( col_type === 'checkbox' ) {
$element.parent('td').animate({'background-color':'#fff'});
if ( value === false ){
$element.parent('td').animate({'background-color':'#DB4A39'});
return false;
}
}
return true;
},
tableClass: 'inputtable custom'
});
// Trigger event
$('#examplexconsole').click(function(e) {
// Get data
console.log(mynewtable.getData());
// Check if data are valid
if ( !mynewtable.isValidated() ){
alert('Not validated');
}
e.preventDefault();
});
Credits and contacts
editTable has been made by me. You can contact me at micc83@gmail.com or twitter for any issue or feauture request.