DataTables with Autocomplete
by John VandenBrook
HTML
<div class="panel-body">
<form id="frmSearch" data-vdl-ajax="true" class="form-inline">
<input type="search" value="" id="searchTerm" class="form-control" name="searchTerm" data-vdl-autocomplete="@Url.Action('Autocomplete')" />
</form>
<br />
<hr />
<form id="frm-example" class="form-inline">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th>Section Name</th>
<th>Application Name</th>
<th><input name="select_all" value="1" id="example-select-all" type="checkbox" /></th>
</tr>
</thead>
</table>
</form>
</div>
<!-- /.panel-body -->
JavaScript
//In first JS file
var editor;
var setDataTable = function (data) {
var jsonSrc = '/Account/AppJsonData?searchTerm=' + data;
editor = new $.fn.dataTable.Editor({
"ajax": jsonSrc,
"table": "#example",
idSrc: 'ApplicationId',
"fields": [
{
label: "Assigned:",
name: "Active",
type: "checkbox",
separator: "|",
options: [
{ label: '', value: 1 }
]
}, {
label: "Application Name:",
name: "ApplicationName"
}, {
label: "Section Name:",
name: "SectionName"
}, { //not used here but I pass a value to in on submit
label: "Last Action:",
name: "LastAction"
}
]
});
$('#example').DataTable({
dom: "Bfrtip",
ajax: jsonSrc,
columns: [
{ "data": "Section.SectionName" },
{ "data": "ApplicationName" },
{
data: "Active",
render: function (data, type, row) {
if (type === 'display') {
return '<input type="checkbox" class="editor-active">';
}
return data;
},
className: "dt-body-center"
}
],
select: {
style: 'os'
//selector: 'td:not(:last-child)' // no row selection on last column
},
"order": [[2, 'des']],
"options": { "emptyTable": "No records to display..." },
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
rowCallback: function (row, data) {
// Set the checked state of the checkbox in the table
$('input.editor-active', row).prop('checked', data.Active === 1);
}
});
$('#example').on('change', 'input.editor-active', function () {
editor
.edit($(this).closest('tr'), false)
.set('Active', $(this).prop('checked') ? 1 : 0)
.set('LastAction', $(this).prop('checked') ? "Checked" : "UnChecked")
.submit();
});
};
//In second JS file
var submitAutocompleteForm = function (event, ui) {
var $input = $(this);
$input.val(ui.item.label);
//CALL TO THE GLOBAL FUNCTION ABOVE
setDataTable("Smith, Bob");
//I use the...