diff --git a/README.md b/README.md index bc3ed93..2c0dd6f 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,75 @@ -jQuery editTable -========= - -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! :) - -To use it you just have to include jQuery and a copy of the plugin in your head or footer: - -```html - - - -``` - -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). - -```js -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... - -```js -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: - -```js -[ - 'checkbox' : { - - html: '', // 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 examples](https://micc83.github.io/editTable/demo/) to understand how it works. - -## Credits and contacts - -ReStable has been made by [me](https://github.com/micc83). You can contact me at micc83@gmail.com or [twitter](https://twitter.com/Micc1983) for any issue or feauture request. +jQuery editTable +========= + +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! :) + +To use it you just have to include jQuery and a copy of the plugin in your head or footer: + +```html + + + +``` + +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). + +```js +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... + +```js +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 +mytable.update(headerCols , rowTemplate); // Update headerCols:[] and rowTemplate: [] , + // Do mytable.reset(); after update. +``` + +To define a custom field type object: + +```js +[ + 'checkbox' : { + + html: '', // 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 examples](https://micc83.github.io/editTable/demo/) to understand how it works. + +## Credits and contacts + +ReStable has been made by [me](https://github.com/micc83). You can contact me at micc83@gmail.com or [twitter](https://twitter.com/Micc1983) for any issue or feauture request. diff --git a/jquery.edittable.js b/jquery.edittable.js index e9d07d4..ef3d9a9 100644 --- a/jquery.edittable.js +++ b/jquery.edittable.js @@ -1,309 +1,320 @@ -/*! editTable v0.2.0 by Alessandro Benoit */ -(function ($, window, i) { - - 'use strict'; - - $.fn.editTable = function (options) { - - // Settings - var s = $.extend({ - data: [['']], - tableClass: 'inputtable', - jsonData: false, - headerCols: false, - maxRows: 999, - first_row: true, - row_template: false, - field_templates: false, - validate_field: function (col_id, value, col_type, $element) { - return true; - } - }, options), - $el = $(this), - defaultTableContent = '', - $table = $('', { - class: s.tableClass + ((s.first_row) ? ' wh' : ''), - html: defaultTableContent - }), - defaultth = '', - colnumber, - rownumber, - reset, - is_validated = true; - - // Increment for IDs - i = i + 1; - - // Build cell - function buildCell(content, type) { - content = (content === 0) ? "0" : (content || ''); - // Custom type - if (type && 'text' !== type){ - var field = s.field_templates[type]; - return ''; - } - // Default - return ''; - } - - // Build row - function buildRow(data, len) { - - var rowcontent = '', b; - - data = data || ''; - - if (!s.row_template) { - // Without row template - for (b = 0; b < (len || data.length); b += 1) { - rowcontent += buildCell(data[b]); - } - } else { - // With row template - for (b = 0; b < s.row_template.length; b += 1) { - // For each field in the row - rowcontent += buildCell(data[b], s.row_template[b]); - } - } - - return $('', { - html: rowcontent + '' - }); - - } - - // Check button status (enable/disabled) - function checkButtons() { - if (colnumber < 2) { - $table.find('.delcol').addClass('disabled'); - } - if (rownumber < 2) { - $table.find('.delrow').addClass('disabled'); - } - if (s.maxRows && rownumber === s.maxRows) { - $table.find('.addrow').addClass('disabled'); - } - } - - // Fill table with data - function fillTableData(data) { - - var a, crow = Math.min(s.maxRows, data.length); - - // Clear table - $table.html(defaultTableContent); - - // If headers or row_template are set - if (s.headerCols || s.row_template) { - - // Fixed columns - var col = s.headerCols || s.row_template; - - // Table headers - for (a = 0; a < col.length; a += 1) { - var col_title = s.headerCols[a] || ''; - $table.find('thead tr').append(''); - } - - // Table content - for (a = 0; a < crow; a += 1) { - // For each row in data - buildRow(data[a], col.length).appendTo($table.find('tbody')); - } - - } else if ( data[0] ) { - - // Variable columns - for (a = 0; a < data[0].length; a += 1) { - $table.find('thead tr').append(defaultth); - } - - for (a = 0; a < crow; a += 1) { - buildRow(data[a]).appendTo($table.find('tbody')); - } - - } - - // Append missing th - $table.find('thead tr').append(''); - - // Count rows and columns - colnumber = $table.find('thead th').length - 1; - rownumber = $table.find('tbody tr').length; - - checkButtons(); - } - - // Export data - function exportData() { - var row = 0, data = [], value; - - is_validated = true; - - $table.find('tbody tr').each(function () { - - row += 1; - data[row] = []; - - $(this).find('td:not(:last-child)').each(function (i, v) { - if ( s.row_template && 'text' !== s.row_template[i] ){ - var field = s.field_templates[s.row_template[i]], - el = $(this).find($(field.html).prop('tagName')); - - value = field.getValue(el); - if ( !s.validate_field(i, value, s.row_template[i], el) ){ - is_validated = false; - } - data[row].push(value); - } else { - value = $(this).find('input[type="text"]').val(); - if ( !s.validate_field(i, value, 'text', v) ){ - is_validated = false; - } - data[row].push(value); - } - }); - - }); - - // Remove undefined - data.splice(0, 1); - - return data; - } - - // Fill the table with data from textarea or given properties - if ($el.is('textarea')) { - - try { - reset = JSON.parse($el.val()); - } catch (e) { - reset = s.data; - } - - $el.after($table); - - // If inside a form set the textarea content on submit - if ($table.parents('form').length > 0) { - $table.parents('form').submit(function () { - $el.val(JSON.stringify(exportData())); - }); - } - - } else { - reset = (JSON.parse(s.jsonData) || s.data); - $el.append($table); - } - - fillTableData(reset); - - // Add column - $table.on('click', '.addcol', function () { - - var colid = parseInt($(this).closest('tr').children().index($(this).parent('th')), 10); - - colnumber += 1; - - $table.find('thead tr').find('th:eq(' + colid + ')').after(defaultth); - - $table.find('tbody tr').each(function () { - $(this).find('td:eq(' + colid + ')').after(buildCell()); - }); - - $table.find('.delcol').removeClass('disabled'); - - return false; - }); - - // Remove column - $table.on('click', '.delcol', function () { - - if ($(this).hasClass('disabled')) { - return false; - } - - var colid = parseInt($(this).closest('tr').children().index($(this).parent('th')), 10); - - colnumber -= 1; - - checkButtons(); - - $(this).parent('th').remove(); - - $table.find('tbody tr').each(function () { - $(this).find('td:eq(' + colid + ')').remove(); - }); - - return false; - }); - - // Add row - $table.on('click', '.addrow', function () { - - if ($(this).hasClass('disabled')) { - return false; - } - - rownumber += 1; - - $(this).closest('tr').after(buildRow(0, colnumber)); - - $table.find('.delrow').removeClass('disabled'); - - checkButtons(); - - return false; - }); - - // Delete row - $table.on('click', '.delrow', function () { - - if ($(this).hasClass('disabled')) { - return false; - } - - rownumber -= 1; - - checkButtons(); - - $(this).closest('tr').remove(); - - $table.find('.addrow').removeClass('disabled'); - - return false; - }); - - // Select all content on click - $table.on('click', 'input', function () { - $(this).select(); - }); - - // Return functions - return { - // Get an array of data - getData: function () { - return exportData(); - }, - // Get the JSON rappresentation of data - getJsonData: function () { - return JSON.stringify(exportData()); - }, - // Load an array of data - loadData: function (data) { - fillTableData(data); - }, - // Load a JSON rappresentation of data - loadJsonData: function (data) { - fillTableData(JSON.parse(data)); - }, - // Reset data to the first instance - reset: function () { - fillTableData(reset); - }, - isValidated: function () { - return is_validated; - } - }; - }; - +/*! editTable v0.2.0 by Alessandro Benoit */ +(function ($, window, i) { + + 'use strict'; + + $.fn.editTable = function (options) { + + // Settings + var s = $.extend({ + data: [['']], + tableClass: 'inputtable', + jsonData: false, + headerCols: false, + maxRows: 999, + first_row: true, + row_template: false, + field_templates: false, + validate_field: function (col_id, value, col_type, $element) { + return true; + } + }, options), + $el = $(this), + defaultTableContent = '', + $table = $('
+ -' + field.setValue(field.html, content)[0].outerHTML + '
+ -' + col_title + '
', { + class: s.tableClass + ((s.first_row) ? ' wh' : ''), + html: defaultTableContent + }), + defaultth = '', + colnumber, + rownumber, + reset, + is_validated = true; + + // Increment for IDs + i = i + 1; + + // Build cell + function buildCell(content, type) { + content = (content === 0) ? "0" : (content || ''); + // Custom type + if (type && 'text' !== type) { + var field = s.field_templates[type]; + return ''; + } + // Default + return ''; + } + + // Build row + function buildRow(data, len) { + + var rowcontent = '', b; + + data = data || ''; + + if (!s.row_template) { + // Without row template + for (b = 0; b < (len || data.length); b += 1) { + rowcontent += buildCell(data[b]); + } + } else { + // With row template + for (b = 0; b < s.row_template.length; b += 1) { + // For each field in the row + rowcontent += buildCell(data[b], s.row_template[b]); + } + } + + return $('', { + html: rowcontent + '' + }); + + } + + // Check button status (enable/disabled) + function checkButtons() { + if (colnumber < 2) { + $table.find('.delcol').addClass('disabled'); + } + if (rownumber < 2) { + $table.find('.delrow').addClass('disabled'); + } + if (s.maxRows && rownumber === s.maxRows) { + $table.find('.addrow').addClass('disabled'); + } + } + + // Fill table with data + function fillTableData(data) { + + var a, crow = Math.min(s.maxRows, data.length); + + // Clear table + $table.html(defaultTableContent); + + // If headers or row_template are set + if (s.headerCols || s.row_template) { + + // Fixed columns + var col = s.headerCols || s.row_template; + + // Table headers + for (a = 0; a < col.length; a += 1) { + var col_title = s.headerCols[a] || ''; + $table.find('thead tr').append(''); + } + + // Table content + for (a = 0; a < crow; a += 1) { + // For each row in data + buildRow(data[a], col.length).appendTo($table.find('tbody')); + } + + } else if (data[0]) { + + // Variable columns + for (a = 0; a < data[0].length; a += 1) { + $table.find('thead tr').append(defaultth); + } + + for (a = 0; a < crow; a += 1) { + buildRow(data[a]).appendTo($table.find('tbody')); + } + + } + + // Append missing th + $table.find('thead tr').append(''); + + // Count rows and columns + colnumber = $table.find('thead th').length - 1; + rownumber = $table.find('tbody tr').length; + + checkButtons(); + } + + // Update settings - headerCols and rowTemplate + function updateSettings(headerCols = null, rowTemplate = null) { + if (rowTemplate != null) s.row_template = rowTemplate; + if (headerCols != null) s.headerCols = headerCols; + } + + // Export data + function exportData() { + var row = 0, data = [], value; + + is_validated = true; + + $table.find('tbody tr').each(function () { + + row += 1; + data[row] = []; + + $(this).find('td:not(:last-child)').each(function (i, v) { + if (s.row_template && 'text' !== s.row_template[i]) { + var field = s.field_templates[s.row_template[i]], + el = $(this).find($(field.html).prop('tagName')); + + value = field.getValue(el); + if (!s.validate_field(i, value, s.row_template[i], el)) { + is_validated = false; + } + data[row].push(value); + } else { + value = $(this).find('input[type="text"]').val(); + if (!s.validate_field(i, value, 'text', v)) { + is_validated = false; + } + data[row].push(value); + } + }); + + }); + + // Remove undefined + data.splice(0, 1); + + return data; + } + + // Fill the table with data from textarea or given properties + if ($el.is('textarea')) { + + try { + reset = JSON.parse($el.val()); + } catch (e) { + reset = s.data; + } + + $el.after($table); + + // If inside a form set the textarea content on submit + if ($table.parents('form').length > 0) { + $table.parents('form').submit(function () { + $el.val(JSON.stringify(exportData())); + }); + } + + } else { + reset = (JSON.parse(s.jsonData) || s.data); + $el.append($table); + } + + fillTableData(reset); + + // Add column + $table.on('click', '.addcol', function () { + + var colid = parseInt($(this).closest('tr').children().index($(this).parent('th')), 10); + + colnumber += 1; + + $table.find('thead tr').find('th:eq(' + colid + ')').after(defaultth); + + $table.find('tbody tr').each(function () { + $(this).find('td:eq(' + colid + ')').after(buildCell()); + }); + + $table.find('.delcol').removeClass('disabled'); + + return false; + }); + + // Remove column + $table.on('click', '.delcol', function () { + + if ($(this).hasClass('disabled')) { + return false; + } + + var colid = parseInt($(this).closest('tr').children().index($(this).parent('th')), 10); + + colnumber -= 1; + + checkButtons(); + + $(this).parent('th').remove(); + + $table.find('tbody tr').each(function () { + $(this).find('td:eq(' + colid + ')').remove(); + }); + + return false; + }); + + // Add row + $table.on('click', '.addrow', function () { + + if ($(this).hasClass('disabled')) { + return false; + } + + rownumber += 1; + + $(this).closest('tr').after(buildRow(0, colnumber)); + + $table.find('.delrow').removeClass('disabled'); + + checkButtons(); + + return false; + }); + + // Delete row + $table.on('click', '.delrow', function () { + + if ($(this).hasClass('disabled')) { + return false; + } + + rownumber -= 1; + + checkButtons(); + + $(this).closest('tr').remove(); + + $table.find('.addrow').removeClass('disabled'); + + return false; + }); + + // Select all content on click + $table.on('click', 'input', function () { + $(this).select(); + }); + + // Return functions + return { + // Get an array of data + getData: function () { + return exportData(); + }, + // Get the JSON rappresentation of data + getJsonData: function () { + return JSON.stringify(exportData()); + }, + // Load an array of data + loadData: function (data) { + fillTableData(data); + }, + // Load a JSON rappresentation of data + loadJsonData: function (data) { + fillTableData(JSON.parse(data)); + }, + // Reset data to the first instance + reset: function () { + fillTableData(reset); + }, + isValidated: function () { + return is_validated; + }, + //update headerCols and rowTemplate + update: function (headerCols, rowTemplate) { + updateSettings(headerCols, rowTemplate); + }, + + }; + }; + })(jQuery, this, 0); \ No newline at end of file
+ -' + field.setValue(field.html, content)[0].outerHTML + '
+ -' + col_title + '