First I initiate all datatables by the following code (there are more options, but I'm adding a minimum for this example). The code bellow is working and start all datatables, if the datatable has a search, it'll initialise the fnServerParams with the parameters. (the parameters are going to the function on the codebehind and working).
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var e = {
sPaginationType: "full_numbers",
};
// If has external filters
if(!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
e.fnServerParams = function (aoData) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
}
jQuery(this).dataTable(e);
});
}
The problem is when I call my function RefreshDataTables() by a click/change event. In the function I used this simplified version to refresh:
PS: All code below is to be interpreted that is inside RefreshDataTables()
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var $oTable = jQuery(this).dataTable();
$oTable.fnDraw();
});
}
But it doesn't update the changes on the inputs/selects of the search. it keep the same from the before. So I tried this code base on this answer:
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var $oTable = jQuery(this).dataTable();
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
$oTable._fnServerParams = function (aoData) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
$oTable.fnDraw();
});
}
But it didn't work. There is no error, but the data is still the same, without any change.
You're querying values of INPUT and SELECT only once during initialization. Instead you should do it every time the data is requested from the server.
So you can modify your initialization code so that you retrieve INPUT and SELECT values on every call to function defined with fnServerParams.
Below I just moved your code into fnServerParams callback.
var dt = jQuery(".dataTable");
if(jQuery().dataTable && dt.length > 0) {
dt.each(function () {
var e = {
sPaginationType: "full_numbers",
fnServerParams: function(aoData){
// If has external filters
if(!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v){
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
for (var i=0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push( { "name": filter.name, "value": filter.value } );
}
}
}
}
};
jQuery(this).dataTable(e);
});
}
Then your RefreshDataTables() calling $oTable.fnDraw() should work.
See the example below for code and demonstration. Please note, that I'm using jQuery Mockjax plug-in just for the sake of demonstrating Ajax request, it's not needed for production code.
$(document).ready(function() {
// AJAX emulation for demonstration only
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings) {
console.log("Request data: ", settings.data);
this.responseText = {
"aaData": [
[
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
],
[
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
],
[
"Trident",
"Internet Explorer 5.5",
"Win 95+",
"5.5",
"A"
]
]
};
}
});
$('#example').dataTable({
"sAjaxSource": "/test/0",
"bServerSide": true,
"fnServerParams": function(aoData) {
// If has external filters
if (!!jQuery(this).data("searchbox")) {
var search_box = jQuery(jQuery(this).data("searchbox"));
var additional_filters = [];
jQuery.each(search_box.find('input,select'), function(i, v) {
additional_filters.push({
name: jQuery(v).attr('name'),
value: jQuery(v).val()
});
});
if (additional_filters.length > 0) {
for (var i = 0; i < additional_filters.length; i++) {
var filter = additional_filters[i];
aoData.push({
"name": filter.name,
"value": filter.value
});
}
}
}
}
});
$('#btn').on('click', function(){
$('#example').dataTable().fnDraw();
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.9.4/css/jquery.dataTables.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<p id="searchbox">
<input type="text" name="param1" value="" placeholder="param1">
<button id="btn" type="button">Search</button>
</p>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" data-searchbox="#searchbox">
<thead>
<tr>
<th width="20%">Rendering engine</th>
<th width="25%">Browser</th>
<th width="25%">Platform(s)</th>
<th width="15%">Engine version</th>
<th width="15%">CSS grade</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>
</table>
</body>
</html>
Related
Javascript beginner here, trying to learn by doing, my question is, here i have a table which is filled with information already and below it is select tag which is fetched from url. My question is i want to fill the table again but with the information of select tag ( depending on which option user choose from select tag, table gets filled with that information). here is select tags data
[
{
"id": "1111",
"mygoals": "getmarried",
"future": "married",
},
{
"id": "2222",
"mygoals": "getmarried",
"future": "married",
},
{
"id": "33333",
"mygoals": "getmarried",
"future": "married",
}
]
Here is my code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table table-responsive-sm ">
<thead>
<tr>
<th>id</th>
<th>mygoals</th>
<th>future</th>
</tr>
</thead>
<tbody id="t">
</tbody>
<thead>
<tr>
<th>id</th>
<th>mygoals</th>
<th>future</th>
</tr>
</thead>
<tbody id="t2">
</tbody>
</table>
<select id="Select" name="name"></select>
</div>
<script>
fetch("https://asdasd.free.beeceptor.com/a", {
method: "GET",
headers: {
"x-api-key": "p*****w"
}
}).then(res =>{
res.json().then(t => {
console.log(t);
var p ="";
var p2 ="";
p +="<tr>";
p += "<td>"+t.id+"</td>";
p += "<td>"+t.mygoals+"</td>";
p += "<td>"+t.future+"</td>";
p2 += "<td>"+t.id+"</td>";
p2 += "<td>"+t.mygoals+"</td>";
p2 += "<td>"+t.future+"</td></tr>";
document.getElementById("t").insertAdjacentHTML("beforeend", p);
document.getElementById("t2").insertAdjacentHTML("beforeend", p2);
}
)
}).catch(err => {
console.log("ERROR: " + err);
});
fetch("https:******.com/", {
method: "GET",
headers: {
"x-api-key": "p*****w"
}
}).then(res =>{
res.json().then(t => {
for (var i = 0; i < t.length; i++) {
var s = document.getElementById("Select");
var o = document.createElement("option");
option.text = t[i].id+ ' ' + t[i].mygoals;
s.add(o);
}
}
)
})
</script>
</body>
</html>
If you need to populate a table with data, once you get the JSON from your XHR fetch, you can just iterate over the data and build table rows.
I am not sure what you mean, by populating the table by the select options. If need be, please provide a full use-case, but I interpret is as you want to fill the table based on the selection.
See the example below.
const tableEl = document.querySelector('.table');
const selectEl = document.querySelector('#select');
// Only show the record that matched the selection.
selectEl.addEventListener('change', e => {
// Or make a call to a different JSON endpoint...
populateTableWithJSON(tableEl, getJsonData().filter(record => {
return record.id === e.target.value;
}));
});
populateTableWithJSON(tableEl, getJsonData());
populateSelectWithJSON(selectEl, getJsonData(), {
idFn : r => r.id,
displayFn : r => `${r.id} ${r.mygoals}`
});
function populateSelectWithJSON(select, jsonData, opts={}) {
emptyElement(select);
jsonData.forEach((record, index) => {
let id = opts.idFn != null ? opts.idFn(record) : record.id || index;
let text = opts.displayFn != null ? opts.displayFn(record) : record.text || '';
select.appendChild(new Option(text, id));
});
}
function populateTableWithJSON(table, jsonData) {
let tbody = table.querySelector('tbody');
emptyElement(tbody);
if (jsonData != null && jsonData.length > 0) {
let headers = table.querySelectorAll('thead > tr th');
let fields = headers.length
? Array.from(headers).map(th => th.textContent)
: Object.keys(jsonData[0]);
jsonData.forEach(record => {
let tr = document.createElement('TR');
fields.forEach(field => {
let td = document.createElement('TD');
td.textContent = record[field];
tr.appendChild(td);
});
tbody.appendChild(tr);
});
}
}
function emptyElement(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function getJsonData() {
return [{
"id": "1111",
"mygoals": "getmarried",
"future": "married",
}, {
"id": "2222",
"mygoals": "getmarried",
"future": "married",
}, {
"id": "33333",
"mygoals": "getmarried",
"future": "married",
}];
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<div class="container">
<table class="table table-responsive-sm ">
<thead>
<tr>
<th>id</th>
<th>mygoals</th>
<th>future</th>
</tr>
</thead>
<tbody></tbody>
</table>
<select id="select" name="name"></select>
</div>
I am using gijgo grid to bind data. I did it two ways using gijgo grid.
1)First Binding data with html helpers to html table and doing CRUD with Gijgo,it binds data,do CRUD but does not reload grid on add,edit and delete.
<table id="grid">
<thead>
<tr>
<th width="56">ID</th>
<th data-sortable="true">Brand</th>
<th data-sortable="true">Model</th>
<th width="64" data-tmpl="<span class='material-icons gj-cursor-pointer'>edit</span>" align="center" data-events="click: Edit"></th>
<th width="64" data-tmpl="<span class='material-icons gj-cursor-pointer'>delete</span>" align="center" data-events="click: Delete"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Brand)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model)
</td>
</tr>
}
</tbody>
</table>
in delete function,grid doesn't reload after deleting
function Delete(e) {
if (confirm('Are you sure?')) {
$.ajax({ url: '/Home/Delete', data: { id: e.data.id }, method: 'POST' })
.done(function () {
//grid.reload({ page: 1});
grid.reload();
})
.fail(function () {
alert('Failed to delete.');
});
}
}
2) Then I did a different implementation of gijgo grid binding data via ajax call of gijgo using this example
Gijgo Grid example
The Get function returns JSON
public JsonResult Get(int? page, int? limit, string sortBy, string direction, string brand, string model)
{
List<CarsViewModel> records;
int total;
var query = _context.Cars.Select(p => new CarsViewModel
{
Id = p.Id,
Brand = p.Brand,
Model = p.Model
});
if (!string.IsNullOrWhiteSpace(model))
{
query = query.Where(q => q.Model != null && q.Model.Contains(model));
}
if (!string.IsNullOrWhiteSpace(brand))
{
query = query.Where(q => q.Brand != null && q.Brand.Contains(brand));
}
if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
{
if (direction.Trim().ToLower() == "asc")
{
switch (sortBy.Trim().ToLower())
{
case "brand":
query = query.OrderBy(q => q.Brand);
break;
case "model":
query = query.OrderBy(q => q.Model);
break;
}
}
else
{
switch (sortBy.Trim().ToLower())
{
case "brand":
query = query.OrderByDescending(q => q.Brand);
break;
case "model":
query = query.OrderByDescending(q => q.Model);
break;
}
}
}
//else
//{
// query = query.OrderBy(q => q.o);
//}
total = query.Count();
if (page.HasValue && limit.HasValue)
{
int start = (page.Value - 1) * limit.Value;
records = query.Skip(start).Take(limit.Value).ToList();
}
else
{
records = query.ToList();
}
return this.Json(new { records, total }, JsonRequestBehavior.AllowGet);
}
jQuery(document).ready(function ($) {
grid = $('#grid').grid({
primaryKey: 'Id',
dataSource: '/Home/Get',
columns: [
{ field: 'Id', width: 56 },
{ field: 'Brand', sortable: true },
{ field: 'Model', sortable: true },
{ width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">edit</span>', align: 'center', events: { 'click': Edit } },
{ width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">delete</span>', align: 'center', events: { 'click': Delete } }
],
pager: { limit: 5 }
});
dialog = $('#dialog').dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 360
});
$('#btnAdd').on('click', function () {
$('#Id').val('');
$('#Brand').val('');
$('#Model').val('');
dialog.open('Add Car');
});
$('#btnSave').on('click', Save);
$('#btnCancel').on('click', function () {
dialog.close();
});
$('#btnSearch').on('click', function () {
grid.reload({ page: 1, name: $('#txtBrand').val(), nationality: $('#txtModel').val() });
});
$('#btnClear').on('click', function () {
$('#txtBrand').val('');
$('#txtModel').val('');
grid.reload({ brand: '', model: '' });
});});
which results in JSON returned in this format
{"records":[{"Id":7,"Brand":"toyota","Model":"matrix"},{"Id":8,"Brand":"Mazda","Model":"M3"}],"total":2} and gives error unable to bind data like
SyntaxError: Unexpected token o in JSON at position 1
If I remove the record and total section and put raw json as datasource like this
[{"Id":7,"Brand":"toyota","Model":"matrix"},{"Id":8,"Brand":"Mazda","Model":"M3"}]
then data is bound but again grid.reload() doesnt work. I am really frustrated why this issues are there. First the gijgo grid server side controller code returns JSON dataas record with total and then I am not able to bind it with the code that gijgo has provided in jquery. Then grid.reload() isn't working
Could you review our ASP.NET examples where everything is setup correctly. You can find them at https://github.com/atatanasov/gijgo-asp-net-examples
I really tried hard to refresh datatable with new data but couldn't achieve it. I initialize datatable with ng-repeat and get the data from api. Any idea would be perfect. Here is my html code:
<table class="table table-bordered table-striped table-hover js-dataTable-full dt-responsive" width="100%" id="dataTableId">
<thead>
<tr>
<th>NO</th>
<th>COMPANY CODE</th>
<th>CREATED DATE</th>
<th>DESCRIPTION</th>
<th>DUE DATE</th>
<th>CREATED BY</th>
<th>STATUS</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="document in documents" ng-if="document.status == 0 || document.status == 2">
<td>{{document.group_order_id}}</td>
<td>{{document.company.code}}</td>
<td>{{document.created}}</td>
<td>{{document.description}}</td>
<td>{{document.due_date}}</td>
<td>{{document.created_by_user.first_name}} {{document.created_by_user.last_name}}</td>
<td><span>Status</span></td>
</tr>
</tbody>
</table>
And here is my controller:
// Init full DataTable, for more examples you can check out https://www.datatables.net/
var initDataTableFull = function () {
if (!$.fn.dataTable.isDataTable('.js-dataTable-full')) {
jQuery('.js-dataTable-full').dataTable({
"language": {
"sProcessing": "İşleniyor...",
"sLengthMenu": "Sayfada _MENU_ Kayıt Göster",
"sZeroRecords": "Eşleşen Kayıt Bulunmadı",
"sInfo": " _TOTAL_ Kayıttan _START_ - _END_ Arası Kayıtlar",
"sInfoEmpty": "Kayıt Yok",
"sInfoFiltered": "( _MAX_ Kayıt İçerisinden Bulunan)",
"sInfoPostFix": "",
"sSearch": "Bul:",
"sUrl": "",
"oPaginate": {
"sFirst": "İlk",
"sPrevious": "Önceki",
"sNext": "Sonraki",
"sLast": "Son"
}
},
"order" : [[0, "desc"]]
});
}
};
// DataTables Bootstrap integration
var bsDataTables = function () {
var DataTable = jQuery.fn.dataTable;
// Set the defaults for DataTables init
jQuery.extend(true, DataTable.defaults, {
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
renderer: 'bootstrap',
oLanguage: {
sLengthMenu: "_MENU_",
sInfo: "Showing <strong>_START_</strong>-<strong>_END_</strong> of <strong>_TOTAL_</strong>",
oPaginate: {
sPrevious: '<i class="fa fa-angle-left"></i>',
sNext: '<i class="fa fa-angle-right"></i>'
}
}
});
// Default class modification
jQuery.extend(DataTable.ext.classes, {
sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
sFilterInput: "form-control",
sLengthSelect: "form-control"
});
// Bootstrap paging button renderer
DataTable.ext.renderer.pageButton.bootstrap = function (settings, host, idx, buttons, page, pages) {
var api = new DataTable.Api(settings);
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function (container, buttons) {
var i, ien, node, button;
var clickHandler = function (e) {
e.preventDefault();
if (!jQuery(e.currentTarget).hasClass('disabled')) {
api.page(e.data.action).draw(false);
}
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if (jQuery.isArray(button)) {
attach(container, button);
}
else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ? '' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ? '' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if (btnDisplay) {
node = jQuery('<li>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId + '_' + button :
null
})
.append(jQuery('<a>', {
'href': '#'
})
.html(btnDisplay)
)
.appendTo(container);
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
}
}
}
};
attach(
jQuery(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
};
// TableTools Bootstrap compatibility - Required TableTools 2.1+
if (DataTable.TableTools) {
// Set the classes that TableTools uses to something suitable for Bootstrap
jQuery.extend(true, DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info"
},
"select": {
"row": "active"
}
});
// Have the collection use a bootstrap compatible drop down
jQuery.extend(true, DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
});
}
};
var table = $('.js-dataTable-full');
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$timeout(function () {
// Init Datatables
bsDataTables();
initDataTableFull();
});
});
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('--------------', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
table.empty();
table.dataTable()._fnInitialise();
$http({
url: 'https://standards-and-partners-api.azurewebsites.net/documents',
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (response) {
$scope.documents = response.data.data;
$scope.$apply();
});
});
What should I do to reload my datatable with new data ? Thanks guys.
Im new to knockout and loving it so far. I've been trying to build a row editing grid using a simple table with edit links. So far it seemed to be going great but been stuck on this issue where im getting the errors when tying to save and update or canel:
Uncaught TypeError: this.description is not a function
and
Uncaught TypeError: this.editdescription is not a function
Been staring at the code for several hours now can't seem to wrap my head around this one. I am able to replicate the issue in this JSFIDDLE:
http://jsfiddle.net/N2zNk/49/
Would anyone know what is cloging in my code?
Here is my HTML:
<table>
<tr>
<th>ID</th>
<th>Description</th>
<th>Department</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tbody data-bind="template: { name: 'rowTmpl', foreach: products }"></tbody>
</table>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: ID"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: Composante"></td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
</script>
<!-- popup -->
<div id="dialogEditProduct" style="width: 400px; max-width: 100%;" data-role="popup" data-theme="c" data-overlay-theme="a" data-dismissible="false" data-bind="with: selectedProduct">
<div data-role="header" data-position="inline">
<h1 ></h1>
</div>
<div data-role="content" data-theme="c">
<p>
<label>Description:</label>
<input data-bind="value: editDescription" />
</p>
<p>
<label>Composante:</label>
<input data-bind="value: editComposante" />
</p>
<button data-role="button" data-bind="click: function() { Incidents.pvm.acceptEdit(); }">Save</button>
<button data-role="button" data-bind="click: function() { Incidents.pvm.cancelEdit() }">Cancel</button>
</div>
</div>
Here is my code:
function Item(ID, Description, Composante) {
var self = this;
this.ID = ID;
this.Description = ko.observable(Description);
this.Composante = ko.observable(Composante);
this.editDescription = ko.observable(Description);
this.editComposante = ko.observable(Composante);
this.accept = function () {
this.description(this.editdescription);
this.price(this.editPrice);
return true;
}.bind(this);
//reset to originals on cancel
this.cancel = function () {
this.editdescription(this.description);
this.editComposante(this.Composante);
}.bind(this);
}
Incidents = {
pvm: {},
productStore: {
products: [],
init: function (data) {
this.products = $.map(data, function (product) {
return new Item(product.ID, product.Description, product.Composante);
});
}
},
init: function () {
/*emuluate pulling orders from DB*/
/*this will come from server or local web storage*/
var dataFromServer = [{
ID: "123",
Description: "The server x is unavailable",
Composante: "CCD"
}, {
ID: "124",
Description: "The router located downtown is down",
Composante: "CCDD"
}, {
ID: "125",
Description: "Fiber optic cable downtown is flapping",
Composante: "MIG"
}, {
ID: "126",
Description: "Network unvailable at the beaver site",
Composante: "MIC"
}];
this.productStore.init(dataFromServer);
$(function () {
Incidents.pvm = new Incidents.productViewModel(Incidents.productStore.products);
ko.applyBindings(Incidents.pvm);
$("#productList").listview('refresh');
});
},
productViewModel: function (data) {
var self = this;
var productsArray = [];
if (data && data.length > 0) {
productsArray = data;
}
this.products = ko.observableArray(productsArray);
this.selectedProduct = ko.observable();
this.editProduct = function (productToEdit) {
self.selectedProduct(productToEdit);
// Incidents.pvm.selectedProduct(productToEdit);
};
this.acceptEdit = function () {
var selected = Incidents.pvm.selectedProduct();
if (selected.accept()) {
Incidents.pvm.selectedProduct("");
$('#dialogEditProduct').popup('close');
}
};
this.cancelEdit = function () {
Incidents.pvm.selectedProduct().cancel();
Incidents.pvm.selectedProduct("");
$('#dialogEditProduct').popup('close');
};
}
};
ko.bindingHandlers.jqButton = {
init: function (element) {
$(element).button();
},
update: function (element, valueAccessor) {
var currentValue = valueAccessor();
$(element).button("option", "disabled", currentValue.enable === false);
}
};
ko.bindingHandlers.jqmListView = {
init: function (element) {
$(element).listview();
},
update: function (element, valueAccessor) {
$(element).listview('refresh');
}
};
ko.bindingHandlers.openProductDialog = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$.mobile.changePage("#dialogEditProduct", {
role: 'dialog'
});
$("#dialogEditProduct").open();
// $("#dialogEditProduct").trigger('create');
}
}
};
$.extend({
isNumber: function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
}
});
Incidents.init();
Javascript is case sensitive. You have mixed up description and Description. Also, editDescription and editdescription.
I want to populate the data into the datatable but no data is getting populated into the table.
Error I'm getting on debugging is:
Uncaught TypeError: Cannot read property 'getContext' of null
html:
<table class="display table table-bordered table-striped" id="example">
<thead>
<tr>
<th>User Name</th>
<th>Email Id</th>
<th>Group Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.user}}</td>
<td>{{item.email}}</td>
<td>{{item.groupName}}</td>
<td>{{item.createdAt}}</td>
</tr>
</tbody>
</table>
controller:
(function () {
"use strict";
angular.module('app').controller('superAdminController', function ($scope, AuthenticationService, $timeout, $location, $http, myConfig) {
AuthenticationService.loadSuperAdmin(function (response) {
if (response.data.success) {
$scope.populateTable(response.data);
console.log(response.data);
} else {
$scope.items = [];
}
});
$scope.populateTable = function (data) {
$scope.items = data.loadSuperAdminData;
$timeout(function () {
$("#example").dataTable();
}, 200)
};
});
}());
In controller, you can populate your server response like this.
$.post(MY_CONSTANT.url + '/api_name',{
access_token: accessToken
}).then(
function(data) {
var dataArray = [];
data = JSON.parse(data);
var lst = data.list;
lst.forEach(function (column){
var d = {user: "", email: "", group: "", created: ""};
d.user = column.user;
d.email = column.email;
d.groupName = column.group;
d.createdAt = column.created;
dataArray.push(d);
});
$scope.$apply(function () {
$scope.list = dataArray;
// Define global instance we'll use to destroy later
var dtInstance;
$timeout(function () {
if (!$.fn.dataTable) return;
dtInstance = $('#datatable4').dataTable({
'paging': true, // Table pagination
'ordering': true, // Column ordering
'info': true, // Bottom left status text
// Text translation options
// Note the required keywords between underscores (e.g _MENU_)
oLanguage: {
sSearch: 'Search all columns:',
sLengthMenu: '_MENU_ records per page',
info: 'Showing page _PAGE_ of _PAGES_',
zeroRecords: 'Nothing found - sorry',
infoEmpty: 'No records available',
infoFiltered: '(filtered from _MAX_ total records)'
}
});
var inputSearchClass = 'datatable_input_col_search';
var columnInputs = $('tfoot .' + inputSearchClass);
// On input keyup trigger filtering
columnInputs
.keyup(function () {
dtInstance.fnFilter(this.value, columnInputs.index(this));
});
});
// When scope is destroyed we unload all DT instances
// Also ColVis requires special attention since it attaches
// elements to body and will not be removed after unload DT
$scope.$on('$destroy', function () {
dtInstance.fnDestroy();
$('[class*=ColVis]').remove();
});
});
});