jQuery Editable Table Example
by torrobinson
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/torrobinson/jquery-editable-table/jquery-editable-table.min.js"></script>
<table id="sample-table" class="basic-table">
<thead>
<tr>
<th>Id</th>
<th>String with MaxLength(10)</th>
<th>Custom Color Example</th>
<th>Secret Value</th>
<th>Number Example</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="sample-table-add-button" style="margin: auto; display: block;">
Add New Row
</button>
<button id="sample-table-dump-button" style="margin: auto; display: block;">
Dump Data to Console
</button>
CSS
/* Table Stuff */
table.basic-table {
width: 100%;
font-family: sans-serif;
}
table.basic-table th{
border-bottom: 1px solid black;
}
table.basic-table th,
table.basic-table td{
height: 2em;
background-color: white;
}
JavaScript
$.fn.editableTable = function (options) {
// Default options
let defaultOptions = {
cloneProperties: ['padding', 'padding-top', 'padding-bottom', 'padding-left', 'padding-right',
'text-align', 'font', 'font-size', 'font-family', 'font-weight',
'border', 'border-top', 'border-bottom', 'border-left', 'border-right', 'color', 'background-color', 'border-radius'],
columns: []
}
// Overlay default options on user options
options = $.extend({}, defaultOptions, options);
// The instance reference we'll pass to the user
let _instance;
// Class to put on the editor to denote an error
let errorClass = 'error';
// Something to tag the hidden input with
let identifierAttribute = 'table-editor-input';
// Keycodes
let ARROW_LEFT = 37,
ARROW_UP = 38,
ARROW_RIGHT = 39,
ARROW_DOWN = 40,
ENTER = 13,
ESC = 27,
TAB = 9,
CONTROL = 17,
LEFT_WINDOWS = 91,
SELECT_KEY = 93;
// The table element
let element = $(this);
// Show all columns and then hide any hidden ones
element.find('th').show();
options.columns.forEach((col, i) => {
if (col.isHidden !== undefined && col.isHidden) element.find('th').eq(i).hide();
});
// If there are actions, add a final blank table header
if (options.actions !== undefined && options.actions.length > 0) {
// Add header if we don't already have one
if (!element.find('thead tr th[actions]').length) {
element.find('thead tr').append($('<th actions></th>'));
}
}
// The textbox allowing user input. Only add if there's not already an editor input control around
let editor;
let existingEditor = element.parent().find(`input[${identifierAttribute}]`);
if (existingEditor.length) {
editor = existingEditor.first();
}
else {
editor = $('<input>');
}
// Add it to the DOM
...