Datatables - not able to put colun chooser - javascript

I have a datatable whose data I am populating as follows. I need to add column chooser to the below function. Can somebody tell me where to place the columns array in the below code.
function(jsonResponse)
{
$("#example").dataTable().fnClearTable();
var data = "jsonResponse."+"controlKpiList";
$.each(eval(data), function(id1, value) {
$("#example").dataTable().fnAddData([
value.ASP_NAME,
value.TIERING_2,
]);
});
}

Related

Get all data from gridmvc including all paging in javascript?

I am trying to fetch data from gridmvc and show graphs using chart.js its working fine but issue is that its showing just with pages. Because i have enabled paging in grid and when i click on next page then next grid data page graphs show, but i want to show graph of complete grid data includes all pages.
<div class="panel-body">
#await Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.ID).Titled("StudentID").Filterable(true);
columns.Add(c => c.Name).Titled("Name").Filterable(true);
columns.Add(c => c.Major).Titled("Major").Filterable(true);
columns.Add(c => c.Minor).Titled("Minor").Filterable(true);
columns.Add(c => c.Email).Titled("Email").Filterable(true);
columns.Add(c => c.Address).Titled("Address").Filterable(true);
columns.Add(c => c.GPA).Titled("GPA").Filterable(true);
}).Searchable(true, false, true).WithPaging(10).ChangePageSize(true).Sortable(true).EmptyText("No data found").Named("GridSearch").RenderAsync()
</div>
Javascript
function LoadChart() {
debugger;
var chartType = parseInt($("#rblChartType input:checked").val());
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
// Map JSON values back to label array
var labels = json.map(function (e) {
return e.Name;
});
console.log(labels); // ["2016", "2017", "2018", "2019"]
// Map JSON values back to values array
var values = json.map(function (e) {
return e.GPA;
});
var chart=BuildChart(labels, values, "Students Name by GPA");
I want to show graphs which include complete data in gridmvc not just on current page.
but issue is that its showing just with pages. Because i have enabled
paging in grid and when i click on next page then next grid data page
graphs show, but i want to show graph of complete grid data includes
all pages.
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
The issue relates the above scripts, since you implement paging, when using the above code to get the table resource, it only gets the current page records, then display the page grahps.
To solve this issue, you could get the records from the page model (Model) or create an action method to get all records, then, use JQuery Ajax method to call this method and get the grid data.
To get records from the page model, in your Asp.net Core MVC application, you could use the Json.Serialize() method to convent the Model to JSON string first, then use JSON.parse() method convent the JSON string to JavaScript Object, then loop through the Object and get all data.
Code like this (Index.cshtml)
#model List<StudentViewModel>
#section Scripts{
<script>
$(function () {
LoadChart();
});
function LoadChart() {
debugger;
//var chartType = parseInt($("#rblChartType input:checked").val());
//var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
var items = JSON.parse('#Json.Serialize(Model)');
$.each(items, function (index, item) {
json.push({ 'StudentID': item.id, 'Name': item.name, 'Major': item.major, 'Major': item.major, 'Email': item.email, 'Address': item.address, 'GPA': item.gpa });
});
//show graphs based on the json array.
The screenshot like this:

How can I reorder the column sequence of my DataTable in my Django App?

I am doing a ajax request to pass some data from Views.py to the HTML file and render it using DataTables() javascript library.
The problem I am facing is that the displayed datatable is not following the column order that I would like to.
I don´t know if the solution is to reorder the json data that the datatable receives or to use some functionallity of DataTables().
What should be the best solution to reorder the table´s column? And how can I apply it to the code bellow?
Views.py
...
def test_table(request):
data_pers = {
'Product':request.GET.get('Product'),
'Length':request.GET.get('Length'),
'Cod':request.GET.get('cod'),
'partnumbetr':'42367325'
}
return JsonResponse({'data_prod':data_prod})
...
HTML
...
$.get('{% url "test_table" %}',
{Product:Product,Length:Length,Cod:Cod},
function (data_prod) {
var data_json_prod=data_prod['data_prod'];
var data_array_prod = [];
var arr_prod = $.map(data_json_prod, function(el) { return el });
data_array_prod.push(arr_prod);
$('#id_prod').DataTable({
destroy: true,
data:data_array_prod,
});
...

dojo dstore insert row

Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.
// Clone a row
theTable = tmxdijit.registry.byId(tableName);
firstRow = theTable.collection.data[theTable.collection.data.length-1];
firstRowDom = theTable.row(firstRow.id);
var cloneRow = json.stringify(firstRow);
cloneRow = json.parse(cloneRow);
// Get the row I want to add before
var theSelected = Object.keys(theTable.selection)[0];
if(theSelected.length > 0) {
var theRowID = theSelected[0];
}
theTable.collection.add(cloneRow, {beforeId: theRowID});
theTable.renderArray([cloneRow]);
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.
For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:
var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
columns: { /* columns */ },
collection: store
});
By default dstore assumes the id property is "id", but you can specify something else:
var store = new StoreClass({ idProperty: "name", data: whatever });
If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):
grid.set('sort', 'name');
To add or remove data, use the store methods put and remove.
var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);
The grid will be notified of the store update and will insert or remove the rows.
The dgrid Using Grids and Stores tutorial has more information and examples.
Instead of this, why don't you add the data directly to the grid store? See if this helps
https://dojotoolkit.org/reference-guide/1.10/dojox/grid/example_Adding_and_deleting_data.html
Adding and Deleting data
If you want to add (remove) data programmatically, you just have to add (remove) it from the underlying data store. Since DataGrid is “DataStoreAware”, changes made to the store will be reflected automatically in the DataGrid.
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
.
<div>
This example shows, how to add/remove rows
</div>
<table data-dojo-type="dojox.grid.DataGrid"
data-dojo-id="grid5"
data-dojo-props="store:store3,
query:{ name: '*' },
rowsPerPage:20,
clientSort:true,
rowSelector:'20px'
style="width: 400px; height: 200px;">
<thead>
<tr>
<th width="200px"
field="name">Country/Continent Name</th>
<th width="auto"
field="type"
cellType="dojox.grid.cells.Select"
options="country,city,continent"
editable="true">Type</th>
</tr>
</thead>
</table>
<div data-dojo-type="dijit.form.Button">
Add Row
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// set the properties for the new item:
var myNewItem = {type: "country", name: "Fill this country name"};
// Insert the new item into the store:
// (we use store3 from the example above in this example)
store3.newItem(myNewItem);
</script>
</div>
<div data-dojo-type="dijit.form.Button">
Remove Selected Rows
<script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
// Get all selected items from the Grid:
var items = grid5.selection.getSelected();
if(items.length){
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
// Delete the item from the data store:
store3.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
</script>
</div>
.
#import "{{ baseUrl }}dijit/themes/nihilo/nihilo.css";
#import "{{ baseUrl }}dojox/grid/resources/nihiloGrid.css";

Display no results using Angular Kendo for kendo list view

I am using Angular Kendo and building one list.
<kendo-mobile-list-view id="myList" class="item-list" k-template="templates.myListTemp" k-data-source="myService.myDataSource">
</kendo-mobile-list-view>
I am using Kendo DataSource and ObservableArray for generating data for my list in my service.
this.myDataSource = new kendo.data.DataSource({ data:this.myObservableArray });
this.myObservableArray.push({ key: "test", id:"test" });
Every is working as expected.
Now I want to display a message when their are no records to display, in the place I am displaying the list, like "NO RECORDS TO DISPLAY, Please Refresh".
How can I achieve this using angular Kendo.
I saw few posts for Kendo JQuery but no solution for Angular Kendo.
Define the grid
$('#grid').kendoGrid({
dataSource: employeeDataSource,
dataBound: function () {
DisplayNoResultsFound($('#grid'));
},
The javascript function 'DisplayNoResultsFound' is as follows
function DisplayNoResultsFound(grid) {
// Get the number of Columns in the grid
var dataSource = grid.data("kendoGrid").dataSource;
var colCount = grid.find('.k-grid-header colgroup > col').length;
// If there are no results place an indicator row
if (dataSource._view.length == 0) {
grid.find('.k-grid-content tbody')
.append('<tr class="kendo-data-row"><td colspan="' + colCount + '" style="text-align:center"><b>No Results Found!</b></td></tr>');
}
// Get visible row count
var rowCount = grid.find('.k-grid-content tbody tr').length;
// If the row count is less that the page size add in the number of missing rows
if (rowCount < dataSource._take) {
var addRows = dataSource._take - rowCount;
for (var i = 0; i < addRows; i++) {
grid.find('.k-grid-content tbody').append('<tr class="kendo-data-row"><td> </td></tr>');
}
}
}
First, you should add a name to your kendo instance(myList):
<kendo-mobile-list-view="myList" id="myList" class="item-list" k-template="templates.myListTemp" k-data-source="myService.myDataSource">
</kendo-mobile-list-view>
Then, in your controller:
$scope.myList.bind('dataBound',DisplayNoResultsFound)
Also you could specify some k-options in the html and read those options(including the dataBound) from the angular controller, this link explains more about it

Angular JS : creating table with json

I've created an application in angular-JS for creating table with dynamic columns from json
For example the JSON structure returning from a service is in the structure where the others field of the main JSON contains another JSON array which is the additional columns,
so all together there will be four additional dynamic columns i.e File 1, File 2, File 3, File 4 each object has value for the corresponding File field, sometime present sometime not present.
$scope.getColumns = function()
{
//console.log( $scope.datas[0].others[0]);
$scope.datas.resultsOrder = new Array();
for ( var i = 0; i < $scope.datas.length; i++)
{
for ( var j = 0; j < $scope.datas[i].others.length; j++)
{
if (countInstances($scope.datas.resultsOrder, $scope.datas[i].others[j].id) < countInstances(
$scope.datas[i].others, $scope.datas[i].others[j].id)){
$scope.datas.resultsOrder.push($scope.datas[i].others[j].id);
}
}
}
$scope.datas.resultsOrder.sort(function(a, b){
return a.localeCompare(b);
});
return $scope.datas.resultsOrder;
}
I've shown the tables with the dynamic columns perfectly using javascript help, but can anyone please tell me some other way for creating the above dynamic table through angular js in a simple way, since in my code I've used javascript complex logic for the creation of dynamic columns which is as shown below
My JS-Fiddle is given below
Demo
This wll create an object called columns where the properties are the names of the dynamic columns ('File 1', 'File 2' etc.)
Controller:
$scope.columns = {};
angular.forEach( $scope.datas, function(data){
angular.forEach( data.others, function(other){
// Set the 'File x' property for each item in the others array
data[other.id] = other.value;
// Add the dyanmic column to the columns object
$scope.columns[other.id] = null;
});
});
View:
<!-- table header -->
<tr>
<th ng-repeat="(column,val) in columns">
<a ng-click="sort_by()"><i>{{column}}</i></a>
</th>
....
</tr>
<!-- data rows -->
<td ng-repeat="(column,v) in columns">{{val[column]}}</td>
Fiddle

Categories

Resources