DataTable add a button to each row - html

Using DataTable API, I am creating a table & adding a button - 'Click' to each table row. Example link below:
https://datatables.net/examples/ajax/null_data_source.html
On the click I am changing text to 'View'. So, after page reload, rather all the buttons displaying default text - 'Click', how to render some buttons with text - 'Click' while the others which were clicked with - 'View'. Experts please share your inputs!!
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": {
"type": "get",
"url": "https://jsonplaceholder.typicode.com/todos",
"dataType": "json",
"dataSrc": function (json) {
var return_data = new Array();
for (var i = 0; i < json.length; i++) {
return_data.push({
'userId': json[i].userId,
'id': json[i].id,
'title': "Test Data"
})
}
return return_data;
}
},
"columns": [
{ 'data': 'userId' },
{ 'data': 'id' },
{ 'data': 'title' },
{ 'data': null }
],
"columnDefs": [
{ targets: 0, className: 'dt-body-center'},
{ targets: 1, className: 'dt-body-center'},
{ targets: 2, className: 'dt-body-center'},
{ targets: -1, width: "150px",
className: 'dt-body-center', defaultContent:
"<button id='btnDetails'>Click</buttom>" }
]});
$('#example tbody').on('click', '[id*=btnDetails]', function () {
$(this).text("View");
});
});
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"> </script>
</head>
<body>
<table id="example" class="display cell-border compact stripe" style="width:100%">
<thead>
<tr>
<th>User Id</th>
<th>Id</th>
<th>Title</th>
<th>Status</th>
</tr>
</thead>
</table>
</body>
</html>

You need a database to persist the state of button. Check below link for server-side processing:
https://datatables.net/examples/data_sources/server_side.html

Related

How to create table with grid filled with data in DataTable?

I have dataTable and returns correct data, but the UI is my problem meaning it does not have columns and sorting are not looking good, here is my logic below and need some help to make look good. I have also attached the back end code for clarity as to why this code, User Interface does not have rows with data grid columns.
[![enter image description here][1]][1]
<!--Building some table here that filters data from db-->
<div style="width:90%; margin:0 auto;">
<table id="eNtsaCourseLists">
<thead>
<tr>
<th>Id</th>
<th>Course</th>
<th>Nickname</th>
<th>Term</th>
<th>Published</th>
<th>CourseLicence</th>
</tr>
</thead>
</table>
</div>
<style>
tr.even {
background-color: #F5F5F5 !important;
}
</style>
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
</center>
<!--Javascript functionality for dataTable-->
<script type="text/javascript" charset="utf8" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
$("#eNtsaCourseLists").dataTable({
"ajax": {
"url": "/Home/loadTableResults",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Id", "autowidth": true },
{ "data": "Course", "autowidth": true },
{ "data": "Nickname", "autowidth": true },
{ "data": "Term", "autowidth": true },
{ "data": "Published", "autowidth": true },
{"data": "CourseLicence", "autowidth":true}
]
});
});
</script>
public ActionResult loadTableResults()
{
//RegCoursesViewModel regCourses = new RegCoursesViewModel();
using (eNtsaRegistration_2 vb = new eNtsaRegistration_2())
{
var data = vb.Courses.OrderBy(n => n.Course).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
}
[1]: https://i.stack.imgur.com/wF76c.png

Kendo grid binding not working in angularjs

I am trying to bind list which i am populating after receiving response from API. I can see the objects into the list but i still didn't understand why kendo grid is not binding datasource. i have code as below.
vm.getAccounts = function () {
acctSearchService.searchAccounts(null, vm.AccountSearchModel)
.then(getAccountsSuccess, getAccountsFailure);
}
vm.accountGridData = [];
function getAccountsSuccess(response) {
vm.accountGridData.push(response.model);
return vm.accountGridData;
}
i am getting result into vm.accountGridData after receiving response from API call and i am trying to bind that to datasource of kendo grid as below.
$("#grid").kendoGrid({
dataSource: { data: vm.accountGridData },
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
Do i need to do anything else to get the data ?
You need to create a directive like this:
app.directive('myDirective', function () {
return {
restrict: 'EA',
scope: {},
template: [].join(''),
controllerAs: 'vm',
controller: function () {
var vm = this;
vm.getAccounts = function () {
acctSearchService.searchAccounts(null, vm.AccountSearchModel).then(getAccountsSuccess, getAccountsFailure);
}
vm.accountGridData = [];
function getAccountsSuccess(response) {
vm.accountGridData.push(response.model);
return vm.accountGridData;
}
},
link: function () {
$("#grid").kendoGrid({
dataSource: { data: vm.accountGridData },
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
}
};
});
And in your html:
<div my-directive></div>
<div id="grid"></div>
You dont need data property in your datasource if you don't implement custom read function for it.
Datasource property should be an array or kendo-datasource object.
Try this:
$("#grid").kendoGrid({
dataSource: vm.accountGridData,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: vm.mainGridColumns
});
And checkout grid documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid
Finally i found the way after fighting. it's in simple one step.
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/angular">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.bootstrap.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.bootstrap.mobile.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.1118/styles/kendo.silver.mobile.min.css" />
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/angular.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.1118/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" ng-app="KendoDemos">
<div ng-controller="MyCtrl">
<kendo-grid k-scope-field="grid" options="mainGridOptions"></kendo-grid>
</div>
</div>
<script>
angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope, $http){
$scope.data = new kendo.data.ObservableArray([]);
$http({
method: 'GET',
type:"json",
url: '//jsonplaceholder.typicode.com/posts'
}).then(function successCallback(response) {
$scope.grid.dataSource.data(response.data);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.mainGridOptions = {
dataSource: {
data: $scope.data,
pageSize: 5
},
sortable: true,
pageable: true,
filterable: {
mode: "row"
},
resizable: true,
columns: [{
field: "userId",
title: "userId",
width: "120px"
},{
field: "id",
title: "ID",
width: "120px"
},{
field: "title",
width: "120px"
},{
field: "body",
width: "120px"
}]
};
})
</script>
</body>
</html>

Update/Assign ng-model object with expression in AngularJs

I am using MEAN stack in my application with AngularJS as my front-end. How to ng-bind the totalsum of value into another input in Agularjs , Actually we have a table and we have used filter to get the totalsum value for Sprice, then we also got sprice totalsum value like 250, then what we exactly expecting is we need to bind this totalsum value into another ng-module input.... for example:- sprice totalsum value is 250, expecting answer of ng-bind value is totalsum value like 250 ...My Plunker. we don't know where we have done the mistake so please look into plunker and help us..
we have a table, in the table we have used filter functionality to get the totalsum value for sprice,we got the answer like 250 using of this <td>{{resultValue | sumOfValue:'sprice'}}</td>.
what we expecting we need to bind the sprice totalsum value to another ng-module like sprice_total input..expecting answer 250...
I have given the plunker as reference plunker please any one knows the solution help us.
My controller:-
sprice totalsum filter:-
.filter('sumOfValue', function () {
return function (data, key) {
debugger;
if (angular.isUndefined(data) && angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data,function(v,k){
if(v.confirm=='cancelled'){
sum = sum + parseFloat(v[key]);
}
});
return sum.toFixed(2);
}
})
My Html:-
<tr ng-repeat="ram in resultValue=(order.orderfood) | filter: {confirm: '!cancelled'}">
<td>{{$index + 1}}</td>
<td>{{ram.sprice }}</td>
</tr>
<tr>
<td>sum</td>
<td>{{resultValue | sumOfValue:'sprice'}}</td>
</tr>
I have tried to use the ng-bind to get the value to another input like :-
<input type="text" ng-model="sprice_total" ng-bind="sprice_total={{resultValue | sumOfValue:'sprice'}}">
please update the plunker as well to know the solution... thanks..
Had created myModelValue directive that will assign your expression to ng-model object
Following is reference link
var app = angular.module('plunker', []);
app.directive('myModelValue', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function (scope, element, attr, controller) {
attr.$observe('myModelValue', function (finalValue) {
scope.model = finalValue;
});
}
};
});
app.filter('sumOfValue', function () {
return function (data, key) {
debugger;
if (angular.isUndefined(data) && angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data, function (v, k) {
if (v.confirm == 'cancelled') {
sum = sum + parseFloat(v[key]);
}
});
return sum.toFixed(2);
}
}).controller('MainCtrl', function ($scope) {
$scope.order =
{
"_id": "5836b64083d9ce0f0078eae8",
"user": {
"_id": "579bdf6123f37f0e00a40deb",
"displayName": "Table 1"
},
"__v": 8,
"total": "1824",
"ordercar": [],
"orderfood": [
{
"qty": "1",
"confirm": "placed",
"sprice": 250,
"price": 250,
"customise": "With Onion,Without Onion",
"name": "Baasha Pizza"
},
{
"qty": "1",
"confirm": "cancelled",
"sprice": 250,
"price": 250,
"customise": "With Onion,Without Onion",
"name": "Baasha Pizza"
}
],
"phone": null,
"order_source": "",
"comment": "",
"payment_mode": "",
"nop": null,
"rating": null,
"bill": false,
"complete": false,
"laundry": false,
"clean": false,
"roomservice": false,
"napkin": false,
"waiter": false,
"water": false,
"name": "fgg",
"created": "2016-11-24T09:43:28.413Z",
"isCurrentUserOwner": true
}
});
/* Put your css in here */
body {
font-size: 14px;
}
table
{
border-collapse:collapse;
}
table, td, th
{
border:1px solid black;
}
td{
padding: 2px;
}
.servicetaxinclusivetrue:before{
color: green!important;
content: "\f00c";
}
.servicetaxinclusivefalse:before{
color: red!important;
content: "\f00d";
}
.servicetaxexclusivetrue:before{
color: green!important;
content: "\f00c";
}
.servicetaxexclusivefalse:before{
color: red!important;
content: "\f00d";
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-controller="MainCtrl">
<table ng-table="tableParams" class="table table-bordered ">
<thead>
<tr>
<th rowspan="2">s.no</th>
<th rowspan="2"> sprice </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ram in resultValue=(order.orderfood) | filter: {confirm: '!cancelled'}">
<td>{{$index + 1}}</td>
<td>{{ram.sprice }}</td>
</tr>
<tr>
<td>sum</td>
<td>{{resultValue | sumOfValue:'sprice'}}</td>
</tr>
</table>
<input type="text" ng-model="sprice_total" my-model-value="{{resultValue | sumOfValue:'sprice'}}">
</body>
</html>
Hope this is what you where expecting

Highchart graph retrieve data from json url

I try to create a high chart graph from a url("http://avare.pe.hu/veri2.json") containing json data. But althrough the datas are retrieved (I tested it as writing it to console) The graph is not displayed. May you please help me?
My datas are
[{"names":["ADANA","ADIYAMAN","AFYONKARAHİSAR","ANKARA","BALIKESİR","BİLECİK","BURSA","ÇANAKKALE","EDİRNE","İSTANBUL","KIRKLARELİ","KOCAELİ","SAKARYA","TEKİRDAĞ","YALOVA"],"count":[3,1,1,4,162,5,532,79,33,714,50,435,66,81,2]}]
..................
The web page
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pasta HighChart Grafiği</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var jsonurl = "http://avare.pe.hu/veri2.json";
var chart;
$.getJSON(jsonurl, function (json) {
var options = {
chart: {
renderTo: 'container',
type: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories:[],
//type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer', size: 160,
dataLabels: {
enabled: false
},
showInLegend: true,
dataLabels: {
enabled: true, connectorWidth: 2, connectorPadding: 1,
format: '<span style="font-size:14px; font-weight:bold">{point.percentage:.1f} %</span>',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
tooltip: {
pointFormat: 'Miktar, <b>{point.y:.1f} kton</b>'
},
series: [{
type:'pie',
data: []
}]
}
// options.series[0] = {};
// options.series[0].name = json[0]['names'];
// options.series[0].data = json[0]['count'];
var names = json[0]['names'];
var count = json[0]['count'];
var arr=new Array(names.length);
console.log(names[0]);
for (i = 0 ; i < name.length; i++) {
arr[i] = [names[i],count[i]];
}
options.series.data = arr;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I have made an example with fixed data, and found one mistake in your code.
You wanted to add data to your series, but you forgot that your series object is an array, so you should add it with this code:
options.series[0].data = arr;
Here you can find an example how your chart will work with this correction: http://jsfiddle.net/worg6jLz/30/

Kendo UI grid is not populated with JSON data

I can't get my Kendo UI grid to populate with my JSON data.
I suspect that it has to do with 'the double' data part in front of my relevant json data.
I'm not sure how I can add a double data mark in my schema. Any help would be much appreciated.
JSON:
{"dsProduct":
{"ttProduct":
[{"ProductId":"Truck","ProductType":5,"Tradeable":true},{"ProductId":"Tractor","ProductType":5,"Tradeable":false}]
}
}
JavaScript/HTML code:
<!doctype html>
<html>
<head>
<title>Kendo Grid with json</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.rtl.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.silver.min.css" rel="stylesheet" />
</head>
<body>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "http://localhost:8810/Kendo/rest/KendoRest",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
},
batch: true,
pageSize: 20,
schema: {
data:
"dsProduct",
model: {
id: "ProductId",
fields: {
ProductId: { type: "string" },
ProductType: { type: "number" },
Tradeable: { type: "boolean" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
{ field: "ProductId", title: "Product Name" },
{ field: "ProductType", title:"Product Type", width: "120px" },
{ field: "Tradeable", title:"Can product be traded?", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "popup"
});
});
</script>
</div>
</body>
</html>
Your definition for the shema.data isn't quite right. Looking at your json, there is a child object under the dsProduct that contains the array. Change your data to dsProduct.ttProduct and it should work.
schema: {
data:
"dsProduct.ttProduct",
model: {
See working sample http://jsbin.com/vevixa/1/edit?html,js,console,output