-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.tablemanager.js
1121 lines (953 loc) · 38.3 KB
/
jquery.tablemanager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Tabledit v1.2.3 ()
* Copyright (c) 2015 Celso Marques
* @author Celso Marques
* @link https://github.com/markcell/jQuery-Tabledit
* Licensed under MIT (https://github.com/markcell/jQuery-Tabledit/blob/master/LICENSE)
*/
/**
* The modified version
* @version 1.2.6
* @author BluesatKV
* @link https://github.com/BluesatKV/jquery-tabledit
*/
/*!
* jTableManager
* @version 1.0
* @author eafarooqi
* @link https://github.com/eafarooqi/jTableManager
*/
if (typeof jQuery === 'undefined') {
throw new Error('jTableManager requires jQuery library.');
}
(function ($) {
'use strict';
//A variable to save the setting data under.
var dataPrefix = '_TableditData';
// Methods
var methods = {
init: function (options) {
// Check if element is 'table'
if (!this.is('table')) {
throw new Error('jTableManager only works when applied to a table.');
}
// jQuery wrapper for clicked element
var $table = this;
// Function - check if value isn't ...
var notNull = function (value) {
return value !== undefined || value !== null || value !== '';
};
// Check User Options isn't empty
if (!notNull(options.columns)) {
// Check if Required options exists
console.log('jTableManager Jquery Plugin not initialize. Set required parameters.');
return this;
}
if (notNull(options.lang) && options.lang in $table.jTableManager.langs) {
// If Language exist in 'jTableManager.langs'
options.lang = options.lang.toLowerCase();
} else {
// Set Language/localization
options.lang = $table.jTableManager.defaults.lang;
}
// Overwrite default options with user provided ones and merge them into "settings" object for multiple instance
var settings = $.extend({}, $table.jTableManager.defaults, options);
// Save settings by using the 'data' function
$(this).data(dataPrefix, $.extend({}, $table.jTableManager.defaults, options || {}));
var $lastEditedRow = 'undefined';
var $lastDeletedRow = 'undefined';
var $lastRestoredRow = 'undefined';
// Set html for all buttons
if (settings.editButton && settings.buttons.edit.html) {
var editButtonHtml = settings.buttons.edit.html;
} else {
var editButtonHtml = $table.jTableManager.langs[settings.lang].btn_edit;
}
if (settings.deleteButton && settings.buttons.delete.html) {
var deleteButtonHtml = settings.buttons.delete.html;
} else {
var deleteButtonHtml = $table.jTableManager.langs[settings.lang].btn_delete;
}
if (settings.confirmButton && settings.buttons.confirm.html) {
var confirmButtonHtml = settings.buttons.confirm.html;
} else {
var confirmButtonHtml = $table.jTableManager.langs[settings.lang].btn_confirm;
}
if (settings.saveButton && settings.buttons.save.html) {
var saveButtonHtml = settings.buttons.save.html;
} else {
var saveButtonHtml = $table.jTableManager.langs[settings.lang].btn_save;
}
if (settings.restoreButton && settings.buttons.restore.html) {
var restoreButtonHtml = settings.buttons.restore.html;
} else {
var restoreButtonHtml = $table.jTableManager.langs[settings.lang].btn_restore;
}
// Output to console with data
if (options.debug) console.log('jTableManager Init -> Element:', $table);
if (options.debug) console.log('jTableManager Init -> dataPrefix:', dataPrefix);
if (options.debug) console.log('jTableManager Init -> Settings: ', settings);
if (options.debug) console.log('jTableManager Init: -----------------------------------');
/**
* Escape HTML
*
* @param {string} value
*/
function escapeHTML(string) {
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '', // "
"'": '', // '
'/': '/',
'`': '`',
'=': '='
};
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
/**
* Send AJAX request to server.
*
* @param {string} action
*/
function ajax(action) {
var jqXHR;
var result;
var serialize = $table.find('.tabledit-input').serialize();
if (!serialize) {
return false;
}
serialize += '&action=' + action;
result = settings.onAjax(action, serialize);
if (result === false) {
return false;
}
settings.method = settings[action + 'method'];
// AJAX SETUP CSRF TOKEN
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, s) {
// Setting the token on the AJAX request
if (!csrfSafeMethod(s.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
// AJAX
jqXHR = $.ajax({
url: settings.url,
type: settings.method,
data: serialize,
dataType: 'json'
});
// DONE callback-manipulation function - success
jqXHR.done(function (data, textStatus, jqXHR) {
// When AJAX call is successfuly
// `data` contains parsed JSON
if (textStatus == 'success') {
if (action === settings.buttons.edit.action) {
$lastEditedRow.removeClass(settings.dangerClass).addClass(settings.successClass);
setTimeout(function () {
//$lastEditedRow.removeClass(settings.successClass);
$table.find('tr.' + settings.successClass).removeClass(settings.successClass);
}, 1400);
}
// Initiate save successful custom callback
settings.onSuccess(data, textStatus, jqXHR);
} else {
// Initiate save failed custom callback
settings.onFail(textStatus);
}
});
// FAIL callback-manipulation function - error
jqXHR.fail(function (jqXHR, textStatus, errorThrown) {
// When AJAX call has failed
if (action === settings.buttons.delete.action) {
$lastDeletedRow.removeClass(settings.mutedClass).addClass(settings.dangerClass);
$lastDeletedRow.find('.tabledit-toolbar button').attr('disabled', false);
$lastDeletedRow.find('.tabledit-toolbar .tabledit-restore-button').hide();
} else if (action === settings.buttons.edit.action) {
$lastEditedRow.addClass(settings.dangerClass);
}
// Initiate save failed custom callback
settings.onFail(jqXHR, textStatus, errorThrown);
// Console log output
console.log('jTableManager Ajax fail => ' + textStatus + ' : ' + errorThrown);
});
// ALWAYS callback-manipulation function - complete
jqXHR.always(function () {
// When AJAX call is complete, will fire upon success or when error is thrown
settings.onAlways();
});
return jqXHR;
}
/**
* Draw jTableManager structure (identifier column, editable columns, toolbar column).
*
* @type {object}
*/
var Draw = {
columns: {
identifier: function () {
// Hide identifier column.
if (settings.hideIdentifier) {
$table.find('th:nth-child(' + parseInt(settings.columns.identifier[0]) + 1 + '), tbody td:nth-child(' + parseInt(settings.columns.identifier[0]) + 1 + ')').hide();
}
// var $td = $table.find('tbody td:nth-child(' + (parseInt(settings.columns.identifier[0]) + 1) + ')');
var $td = $table.find('tbody tr:not(".' + settings.noEditClass + '") td:not(".' + settings.noEditClass + '")').filter(':nth-child(' + (parseInt(settings.columns.identifier[0]) + 1) + ')');
$td.each(function () {
// Get text of this cell.
var text = $.trim($(this).text().replace(/^\s+|\s+$/g, ''));
var text = settings.escapehtml ? escapeHTML(text) : text;
// Create hidden input with row identifier.
var span = '<span class="tabledit-span tabledit-identifier">' + text + '</span>';
var input = '<input class="tabledit-input tabledit-identifier" type="hidden" name="' + settings.columns.identifier[1] + '" value="' + text + '" disabled>';
// Add elements to table cell.
$(this).html(span + input);
// Add attribute "id" to table row.
$(this).parent('tr').attr(settings.rowIdentifier, $.trim($(this).text()));
});
},
editable: function () {
for (var i = 0; i < settings.columns.editable.length; i++) {
var $td = $table.find('tbody tr:not(".' + settings.noEditClass + '") td:not(".' + settings.noEditClass + '")').filter(':nth-child(' + (parseInt(settings.columns.editable[i][0]) + 1) + ')');
$td.each(function () {
// Get text of this cell
// RegEx (Trim Leading and Trailing) -> Before: " a b c d e " / After: "a b c d e"
var text = $.trim($(this).text().replace(/(^\s+|\s+$)/g, ''));
var text = settings.escapehtml ? escapeHTML(text) : text;
// Add pointer as cursor.
if (!settings.editButton) {
$(this).css('cursor', 'pointer');
}
// Create span element.
var span = '<span class="tabledit-span">' + text + '</span>';
var input;
// Section for settings of valid types, values, attributes and other ...
// -----------------------------------
// List of valid types for columnType
var supportedTypes = ["input", "hidden", "number", "select", "textarea"];
// List of valid attributes for columnType 'textarea'
var supportedAttrTextarea = ["rows", "cols", "maxlength", "wrap"];
// -----------------------------------
// Get type from colums user definition
var columnType = settings.columns.editable[i][2];
// Set default element if not of supported type
if ($.inArray(columnType, supportedTypes) == -1) {
columnType = 'input';
}
// Create element by type
switch (columnType) {
case 'input':
// Create text input element.
input = '<input class="tabledit-input ' + settings.inputClass + '" type="text" name="' + settings.columns.editable[i][1] + '" value="' + text + '" style="display: none;" disabled>';
break;
case 'hidden':
// Create text input element.
input = '<input class="tabledit-input ' + settings.inputClass + '" type="hidden" name="' + settings.columns.editable[i][1] + '" value="' + text + '" style="display: none;" disabled>';
break;
case 'number':
// Create text input element.
input = '<input class="tabledit-input ' + settings.inputClass + '" type="number" name="' + settings.columns.editable[i][1] + '" value="' + text + '" style="display: none;" disabled>';
break;
case 'select':
// Check if exists the third parameter of editable array.
if (typeof settings.columns.editable[i][3] !== 'undefined') {
// Create select element.
input = '<select class="tabledit-input ' + settings.inputClass + '" name="' + settings.columns.editable[i][1] + '" style="display: none;" disabled>';
// Create options for select element.
$.each($.parseJSON(settings.columns.editable[i][3]), function (index, value) {
value = $.trim(value);
if (text === value) {
input += '<option value="' + index + '" selected>' + value + '</option>';
} else {
input += '<option value="' + index + '">' + value + '</option>';
}
});
// Create last piece of select element.
input += '</select>';
}
break;
case 'textarea':
// Create textarea element.
input = '<textarea ';
$.each($.parseJSON(settings.columns.editable[i][3]), function (index, value) {
// Ignore attribute if not of supported type
input += ($.inArray(index, supportedAttrTextarea) != -1) ? index + '="' + value + '" ' : '';
});
input += ' class="tabledit-input ' + settings.inputClass + '" name="' + settings.columns.editable[i][1] + '" style="display: none;" disabled>' + text + '</textarea><span class="count_" style="display: none;"><span class="countno_"></span> ' + $table.jTableManager.langs[settings.lang].txt_remain + '</span>';
break;
}
// Add elements and class "view" to table cell.
$(this).html(span + input);
$(this).addClass('tabledit-view-mode');
});
}
},
toolbar: function () {
if (settings.editButton || settings.deleteButton) {
var editButton = '';
var deleteButton = '';
var saveButton = '';
var restoreButton = '';
var confirmButton = '';
// Add toolbar column header if not exists.
if ($table.find('th.tabledit-toolbar-column').length === 0) {
$table.find('tr:first').append('<th class="tabledit-toolbar-column">' + $table.jTableManager.langs[settings.lang].txt_action + '</th>');
}
// Create edit button.
if (settings.editButton) {
editButton = '<button type="button" class="tabledit-edit-button ' + settings.buttons.edit.class + '" style="float: none;">' + editButtonHtml + '</button>';
}
// Create delete button.
if (settings.deleteButton) {
deleteButton = '<button type="button" class="tabledit-delete-button ' + settings.buttons.delete.class + '" style="float: none;">' + deleteButtonHtml + '</button>';
confirmButton = '<button type="button" class="tabledit-confirm-button ' + settings.buttons.confirm.class + '" style="display: none; float: none;">' + confirmButtonHtml + '</button>';
}
// Create save button.
if (settings.editButton && settings.saveButton) {
saveButton = '<button type="button" class="tabledit-save-button ' + settings.buttons.save.class + '" style="display: none; float: none;">' + saveButtonHtml + '</button>';
}
// Create restore button.
if (settings.deleteButton && settings.restoreButton) {
restoreButton = '<button type="button" class="tabledit-restore-button ' + settings.buttons.restore.class + '" style="display: none; float: none;">' + restoreButtonHtml + '</button>';
}
var toolbar = '<div class="tabledit-toolbar ' + settings.toolbarClass + '" style="text-align: left;">\n\
<div class="' + settings.groupClass + '" style="float: none;">' + editButton + deleteButton + '</div>\n\
' + saveButton + '\n\
' + confirmButton + '\n\
' + restoreButton + '\n\
</div></div>';
// Add toolbar column cells for normal cell
$table.find('tbody > tr:not(".' + settings.noEditClass + '")').append('<td class="toolbar" style="white-space: nowrap; width: 1%;">' + toolbar + '</td>');
// Add toolbar column with a ban on row editing
$table.find('tbody > tr.' + settings.noEditClass).append('<td class="toolbar" style="white-space: nowrap; width: 1%;"></td>');
}
}
}
};
/**
* Change to view mode or edit mode with table td element as parameter.
*
* @type object
*/
var Mode = {
view: function (td) {
// Get table row.
var $tr = $(td).parent('tr');
// Disable identifier.
$(td).parent('tr').find('.tabledit-input.tabledit-identifier').prop('disabled', true);
// Hide and disable input element.
$(td).find('.tabledit-input').blur().hide().prop('disabled', true);
// Hide count if exist for textarea
$(td).find('.count_').hide();
// Show span element.
$(td).find('.tabledit-span').show();
// Add "view" class and remove "edit" class in td element.
$(td).addClass('tabledit-view-mode').removeClass('tabledit-edit-mode');
// Update toolbar buttons.
if (settings.editButton) {
$tr.find('button.tabledit-save-button').hide();
$tr.find('button.tabledit-edit-button').removeClass('active').blur();
}
},
edit: function (td) {
Delete.reset(td);
// Get table row.
var $tr = $(td).parent('tr');
// Enable identifier.
$tr.find('.tabledit-input.tabledit-identifier').prop('disabled', false);
// Hide span element.
$(td).find('.tabledit-span').hide();
// Get input element.
var $input = $(td).find('.tabledit-input');
// Enable and show input element.
$input.prop('disabled', false).show();
// Set style for textarea
$(td).find('textarea').css({"resize": "none"});
// Show count if exist for textarea and set style
$(td).find('.count_').css({"color": "#CCC", "display": "block", "float": "right"}).show();
$(td).find('.countno_').html('...');
// Focus on input element.
if (settings.autoFocus) {
// in case if disableSelectAutoFocus is set to false focus will not be set only for select element
if(!$input.is("select") || !settings.disableSelectAutoFocus) {
$input.focus();
// selecting the editable text
if (settings.textSelection == true)
{
$input.select();
}
// setting cursor position to end
// works only if textselection is disabled
if (settings.cursorPosition == 'end' && settings.textSelection == false) {
$input.putCursorAtEnd()
.on("focus", function() {
$input.putCursorAtEnd()
});
}
}
}
// Add "edit" class and remove "view" class in td element.
$(td).addClass('tabledit-edit-mode').removeClass('tabledit-view-mode');
// Update toolbar buttons.
if (settings.editButton) {
$tr.find('button.tabledit-edit-button').addClass('active');
$tr.find('button.tabledit-save-button').show();
}
}
};
/**
* Available actions for edit function, with table td element as parameter or set of td elements.
*
* @type object
*/
var Edit = {
reset: function (td) {
$(td).each(function () {
// Get input element.
var $input = $(this).find('.tabledit-input');
// Get span text.
var text = $.trim($(this).find('.tabledit-span').text());
// Set input/select value with span text.
if ($input.is('select')) {
$input.find('option').filter(function () {
return $.trim($(this).text()) === text;
}).attr('selected', true);
} else {
$input.val(text);
}
// Change to view mode.
Mode.view(this);
});
},
submit: function (td) {
// Send AJAX request to server.
var ajaxResult = ajax(settings.buttons.edit.action);
if (ajaxResult === false) {
return;
}
$(td).each(function () {
// Get input element.
var $input = $(this).find('.tabledit-input');
// Set span text with input/select new value.
if ($input.is('select')) {
$(this).find('.tabledit-span').text($.trim($input.find('option:selected').text()));
} else {
$(this).find('.tabledit-span').text($input.val());
}
// Change to view mode.
Mode.view(this);
});
// Set last edited column and row.
$lastEditedRow = $(td).parent('tr');
}
};
/**
* Available actions for delete function, with button as parameter.
*
* @type object
*/
var Delete = {
reset: function (td) {
// Reset delete button to initial status.
$table.find('.tabledit-confirm-button').hide();
// Remove "active" class in delete button.
$table.find('.tabledit-delete-button').removeClass('active').blur();
},
submit: function (td) {
Delete.reset(td);
// Enable identifier hidden input.
$(td).parent('tr').find('input.tabledit-identifier').attr('disabled', false);
// Send AJAX request to server.
var ajaxResult = ajax(settings.buttons.delete.action);
// Disable identifier hidden input.
$(td).parents('tr').find('input.tabledit-identifier').attr('disabled', true);
if (ajaxResult === false) {
return;
}
// Add class "deleted" to row.
$(td).parent('tr').addClass('tabledit-deleted-row');
// Hide table row.
$(td).parent('tr').addClass(settings.mutedClass).find('.tabledit-toolbar button:not(.tabledit-restore-button)').attr('disabled', true);
// Show restore button.
$(td).find('.tabledit-restore-button').show();
// Set last deleted row.
$lastDeletedRow = $(td).parent('tr');
// Hiding the deleted row
if(settings.hideDeletedRow == true && settings.restoreButton == false)
{
$lastDeletedRow.hide("slow");
}
},
confirm: function (td) {
// Reset all cells in edit mode.
$table.find('td.tabledit-edit-mode').each(function () {
Edit.reset(this);
});
// Add "active" class in delete button.
$(td).find('.tabledit-delete-button').addClass('active');
// Show confirm button.
$(td).find('.tabledit-confirm-button').show();
},
restore: function (td) {
// Enable identifier hidden input.
$(td).parent('tr').find('input.tabledit-identifier').attr('disabled', false);
// Send AJAX request to server.
var ajaxResult = ajax(settings.buttons.restore.action);
// Disable identifier hidden input.
$(td).parents('tr').find('input.tabledit-identifier').attr('disabled', true);
if (ajaxResult === false) {
return;
}
// Remove class "deleted" to row.
$(td).parent('tr').removeClass('tabledit-deleted-row');
// Hide table row.
$(td).parent('tr').removeClass(settings.mutedClass).find('.tabledit-toolbar button').attr('disabled', false);
// Hide restore button.
$(td).find('.tabledit-restore-button').hide();
// Set last restored row.
$lastRestoredRow = $(td).parent('tr');
}
};
// Draw columns
Draw.columns.identifier();
Draw.columns.editable();
Draw.columns.toolbar();
settings.onDraw();
if (settings.deleteButton) {
/**
* Delete one row.
*
* @param {object} event
*/
$table.on('click', 'button.tabledit-delete-button', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
// Get current state before reset to view mode.
var activated = $(this).hasClass('active');
var $td = $(this).parents('td');
Delete.reset($td);
if (!activated) {
Delete.confirm($td);
}
event.handled = true;
}
});
/**
* Delete one row (confirm).
*
* @param {object} event
*/
$table.on('click', 'button.tabledit-confirm-button', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
var $td = $(this).parents('td');
Delete.submit($td);
event.handled = true;
}
});
}
if (settings.restoreButton) {
/**
* Restore one row.
*
* @param {object} event
*/
$table.on('click', 'button.tabledit-restore-button', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
Delete.restore($(this).parents('td'));
event.handled = true;
}
});
}
if (settings.editButton) {
/**
* Activate edit mode on all columns.
*
* @param {object} event
*/
$table.on('click', 'button.tabledit-edit-button', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
var $button = $(this);
// Get current state before reset to view mode.
var activated = $button.hasClass('active');
// Change to view mode columns that are in edit mode.
Edit.reset($table.find('td.tabledit-edit-mode'));
if (!activated) {
// Change to edit mode for all columns in reverse way.
$($button.parents('tr').find('td.tabledit-view-mode').get().reverse()).each(function () {
Mode.edit(this);
});
}
event.handled = true;
}
});
/**
* Save edited row.
*
* @param {object} event
*/
$table.on('click', 'button.tabledit-save-button', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
// Submit and update all columns.
Edit.submit($(this).parents('tr').find('td.tabledit-edit-mode'));
event.handled = true;
}
});
} else {
/**
* Change to edit mode on table td element.
*
* @param {object} event
*/
$table.on(settings.eventType, 'tr:not(.tabledit-deleted-row) td.tabledit-view-mode', function (event) {
if (event.handled !== true) {
// Stop, the default action of the event will not be triggered
event.preventDefault();
// Reset all td's in edit mode.
Edit.reset($table.find('td.tabledit-edit-mode'));
// Change to edit mode.
Mode.edit(this);
event.handled = true;
}
});
/**
* Change event when input is a select element.
*/
$table.on('change', 'select.tabledit-input:visible', function (event) {
if (event.handled !== true) {
// Submit and update the column.
Edit.submit($(this).parent('td'));
event.handled = true;
}
});
/**
* Click event on document element.
*
* @param {object} event
*/
$(document).on('click', function (event) {
var $editMode = $table.find('.tabledit-edit-mode');
// Reset visible edit mode column.
if (!$editMode.is(event.target) && $editMode.has(event.target).length === 0) {
Edit.reset($table.find('.tabledit-input:visible').parent('td'));
}
});
}
/**
* Keypress event on table element.
*
* @param {object} event
*/
$table.on('keypress, keydown', function (event) {
// Get input element with focus or confirmation button.
var $input = $table.find('.tabledit-input:visible');
var $button = $table.find('.tabledit-confirm-button');
if ($input.length > 0) {
var $td = $input.parents('td');
} else if ($button.length > 0) {
var $td = $button.parents('td');
} else {
return;
}
// Key?
switch (event.keyCode) {
case 9: // Tab.
if (!settings.editButton) {
Edit.submit($td);
Mode.edit($td.closest('td').next());
}
break;
case 13: // Enter.
// Stop, the default action of the event will not be triggered
event.preventDefault();
Edit.submit($td);
break;
case 27: // Escape.
Edit.reset($td);
Delete.reset($td);
break;
case 40: // down arrow
if (!settings.editButton && settings.allowArrowKeyMovement == true)
{
var index = $td.index();
var $bottom_tr = $td.parent('tr').next();
var $bottom_td = $bottom_tr.find('td').eq(index);
Edit.submit($td);
Mode.edit($bottom_td);
}
break;
case 38: // up arrow
if (!settings.editButton && settings.allowArrowKeyMovement == true)
{
var index = $td.index();
var $upper_tr = $td.parent('tr').prev();
var $upper_td = $upper_tr.find('td').eq(index);
Edit.submit($td);
Mode.edit($upper_td);
}
break;
}
});
/**
* Keydown event on table textarea.
*
*/
$('textarea').on('change keyup keydown', function () {
var length = $(this).val().length;
// Get maxlength attribute
var maxLength = $(this).attr('maxlength');
// Check the value and get the length of it, store it in a variable
var length = maxLength - length;
// Show result
$(this).parent().find('.countno_').text(length);
});
return this;
},
destroy: function (options) {
// jQuery wrapper for clicked element
var $table = this;
// Output to console with data
if (options.debug) console.log('jTableManager Destroy -> Element:', $(this));
// Remove toolbar column header
$table.find('.tabledit-toolbar-column').remove();
// Remove toolbar
$table.find('.toolbar').remove();
return;
},
update: function (options) {
// jQuery wrapper for clicked element
var $table = this;
// Reload options by using the 'data' function
var defaults = $(this).data(dataPrefix);
// Log output if 'data' not exists
if (!defaults) {
console.log('jTableManager Update -> Data: jTableManager must be initialized before setting options');
return;
}
// Overwrite reload options with user provided ones and merge them into "options" - recursively
var options = $.extend(true, defaults, options);
// Output to console with data
if (options.debug) console.log('jTableManager Update -> Element:', $(this));
if (options.debug) console.log('jTableManager Update -> Settings: ', options);
// Get only debug options in all 'options' and create object from json
// This is only one options for destroy method calling from 'update' method
var debugoption = $.parseJSON(JSON.stringify(options, ['debug']));
// Call 'init' method function with options
methods.destroy.apply(this, [debugoption]);
// Call 'init' method function with options
methods.init.apply(this, [options]);
}
};
// Function to set cursor at the end
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
var $el = $(this),
el = this;
if (!$el.is(":focus")) {
$el.focus();
}
if (el.setSelectionRange)
{
var len = $el.val().length * 2;
// Timeout seems to be required for Blink
setTimeout(function() {
el.setSelectionRange(len, len);
}, 1);
}
else
{
//fallback
$el.val($el.val());
}
// Scroll to the bottom, in case we're in a tall textarea
this.scrollTop = 999999;
});
};
// CALL PLUGIN METHOD
$.fn.jTableManager = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
// Default to "init"
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.jTableManager');
}
};
// SET DEFAULT OPTIONS
$.fn.jTableManager.defaults = {
// Link to server script
url: window.location.href,
// Server request method for action 'edit' and 'delete'
editmethod: 'post',
deletemethod: 'post',
// Class for form inputs
inputClass: 'form-control input-sm',
// Class for buttons toolbar
toolbarClass: 'btn-toolbar',
// Class for buttons group
groupClass: 'btn-group btn-group-sm',
// Class for row when ajax request fails
dangerClass: 'danger',
// Class for row when save changes
successClass: 'success',
// Class for row when is deleted
mutedClass: 'text-muted',
// Class for prohibiting cell editing
noEditClass: 'noedit',
// Trigger to change for edit mode
eventType: 'click',
// Change the name of attribute in td element for the row identifier
rowIdentifier: 'id',
// Hide the column that has the identifier
hideIdentifier: false,