Editor example Select2

First name Last name Phone # Location
First name Last name Phone # Location

The JavaScript shown below is used to initialise the table shown in this example:

(function ($, DataTable) { if (!DataTable.ext.editorFields) { DataTable.ext.editorFields = {}; } var _fieldTypes = DataTable.Editor ? DataTable.Editor.fieldTypes : DataTable.ext.editorFields; _fieldTypes.select2 = { _addOptions: function (conf, opts) { var elOpts = conf._input[0].options; elOpts.length = 0; if (opts) { DataTable.Editor.pairs( opts, conf.optionsPair, function (val, label, i) { elOpts[i] = new Option(label, val); } ); } }, create: function (conf) { conf._input = $('<select/>').attr( $.extend( { id: DataTable.Editor.safeId(conf.id) }, conf.attr || {} ) ); var options = $.extend( { width: '100%' }, conf.opts ); _fieldTypes.select2._addOptions(conf, conf.options || conf.ipOpts); conf._input.select2(options); var open; conf._input .on('select2:open', function () { open = true; }) .on('select2:close', function () { open = false; }); // On open, need to have the instance update now that it is in the DOM this.one('open.select2-' + DataTable.Editor.safeId(conf.id), function () { conf._input.select2(options); if (open) { conf._input.select2('open'); } }); return conf._input[0]; }, get: function (conf) { var val = conf._input.val(); val = conf._input.prop('multiple') && val === null ? [] : val; return conf.separator ? val.join(conf.separator) : val; }, set: function (conf, val) { var field = this.field(conf.name); if (conf.separator && !Array.isArray(val)) { val = val === null ? [] : val.split(conf.separator); } // Clear out any existing tags if (conf.opts && conf.opts.tags) { conf._input.val([]); } // The value isn't present in the current options list, so we need to add it // in order to be able to select it. Note that this makes the set action async! // It doesn't appear to be possible to add an option to select2, then change // its label and update the display var needAjax = false; if (conf.opts && conf.opts.ajax) { if (Array.isArray(val)) { for (var i = 0, ien = val.length; i < ien; i++) { if ( conf._input.find('option[value="' + val[i] + '"]').length === 0 ) { needAjax = true; break; } } } else { if (conf._input.find('option[value="' + val + '"]').length === 0) { needAjax = true; } } } if (needAjax && val) { field.processing(true); var functionData = {}; if (typeof conf.opts.ajax.data === 'function') { functionData = conf.opts.ajax.data({ term: val, page: 0 }); } $.ajax( $.extend( { beforeSend: function (jqXhr, settings) { // Add an initial data request to the server, but don't // override `data` since the dev might be using that var initData = conf.urlDataType === undefined || conf.urlDataType === 'json' ? 'initialValue=true&value=' + JSON.stringify(val) + '&' + $.param(functionData) : $.param( $.extend(functionData, { initialValue: true, value: val }) ); if (typeof conf.opts.ajax.url === 'function') { settings.url = conf.opts.ajax.url(); } if (settings.type === 'GET') { settings.url += settings.url.indexOf('?') === -1 ? '?' + initData : '&' + initData; } else { settings.data = settings.data ? settings.data + '&' + initData : initData; } }, success: function (json) { var addOption = function (option) { if ( conf._input.find('option[value="' + option.id + '"]') .length === 0 ) { $('<option/>') .attr('value', option.id) .text(option.text) .appendTo(conf._input); } }; if (Array.isArray(json)) { for (var i = 0, ien = json.length; i < ien; i++) { addOption(json[i]); } } else if (json.results && Array.isArray(json.results)) { for (var i = 0, ien = json.results.length; i < ien; i++) { addOption(json.results[i]); } } else { addOption(json); } conf._input.val(val).trigger('change', { editor: true }); field.processing(false); } }, conf.opts.ajax ) ); } else { conf._input.val(val).trigger('change', { editor: true }); } }, enable: function (conf) { $(conf._input).removeAttr('disabled'); }, disable: function (conf) { $(conf._input).attr('disabled', 'disabled'); }, // Non-standard Editor methods - custom to this plug-in inst: function (conf) { var args = Array.prototype.slice.call(arguments); args.shift(); return conf._input.select2.apply(conf._input, args); }, update: function (conf, data) { var val = _fieldTypes.select2.get(conf); _fieldTypes.select2._addOptions(conf, data); // Restore null value if it was, to let the placeholder show if (val === null) { _fieldTypes.select2.set.call(this, conf, null); } $(conf._input).trigger('change', { editor: true }); }, focus: function (conf) { if (conf._input.is(':visible') && conf.onFocus === 'focus') { conf._input.select2('open'); } }, owns: function (conf, node) { if ( $(node).closest('.select2-container').length || $(node).closest('.select2').length || $(node).hasClass('select2-selection__choice__remove') ) { return true; } return false; }, canReturnSubmit: function () { return false; } }; })(jQuery, jQuery.fn.dataTable); $(document).ready(function () { var editor = new DataTable.Editor({ ajax: '../php/join.php', table: '#example', fields: [ { label: 'Site:', name: 'users.site', type: 'select2', opts: { ajax: { type: 'POST', url: '/api', dataType: 'json', data: function (params) { let query = { search: params.term, page: params.page || 0, limit: 20, order: 'name ASC', service: 'hotopportunity:app', method: 'getRegisteredContactsSelect2List', WebinarID: $('#WebinarID').val() }; return query; } } } }, { label: 'First name:', name: 'users.first_name' }, { label: 'Last name:', name: 'users.last_name' }, { label: 'Phone #:', name: 'users.phone' } ] }); editor.on('initEdit', function (e, json, data) { editor .field('users.site') .update([data.users.site]) .val(data.users.site); }); //editor.dependent( 'users.site', function ( val, data, callback ) { // return val === '2' ? // London // { hide: 'users.phone' } : // { show: 'users.phone' }; //} ); $('#example').on('click', 'tbody td:not(:first-child)', function (e) { editor.inline(this, { onBlur: 'submit' }); }); $('#example').DataTable({ dom: 'Bfrtip', ajax: { url: '../php/join.php', type: 'POST' }, keys: { editor: editor }, columns: [ { data: 'users.first_name' }, { data: 'users.last_name' }, { data: 'users.phone' }, { data: 'sites.name', editField: 'users.site' } ], select: true, buttons: [ { extend: 'create', editor: editor }, { extend: 'edit', editor: editor }, { extend: 'remove', editor: editor } ] }); });

In addition to the above code, the following JavaScript library files are loaded for use in this example:

    The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:

    This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below:

    The following CSS library files are loaded for use in this example to provide the styling of the table:

      This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is loaded.

      The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side processing scripts can be written in any language, using the protocol described in the DataTables documentation.