I have a question that I think has a easy answer but I cant find how to do it on the forum..
The following code is used to send info to a ajax script when checkbox is checked or unchecked. It now only sent the the data from kwartaal_id to the script. But I also need the column name to be send to the ajax script since i use more of these checkboxes on one page and I need to know which one is triggered. So I need the column name to be posted the same as I do with the row.kwartaal_id. How do I do that? I imagine it would be like this..
"columns": [
{data: 'kwartaal_klant',
render: function ( data, type, row, meta ) {
return ''+data+'';
} } ,
{data: 'kwartaal_notes',
render: function ( data, type, row, meta ) {
return ''+data+'';
} } ,
{data: 'kwartaal_1'},
{data: 'kwartaal_2'},
{data: 'kwartaal_3'},
{data: 'kwartaal_4'},
{data: 'kwartaal_user',
render: function ( data, type, row, meta ) {
return ''+data+'';
} } ,
],
Before:
{targets: [2,3,4,5],
render: function ( data, type, row ) {
if ( type !== 'display' )
return ""; //Empty cell content
else { //if column data is 1 then set attr to checked, use row id as input id (plus prefix)
return '<label class="switch"><input type="checkbox" ' + ((data == 1) ? 'checked' : '') + ' value="' + row.kwartaal_id + '" class="active" /><div class="slider round"><span class="on">ON</span><span class="off">OFF</span></div></label>';
}
return data;
},
After: (added the ''name'' attribute)
{targets: [2,3,4,5],
render: function ( data, type, row ) {
if ( type !== 'display' )
return ""; //Empty cell content
else { //if column data is 1 then set attr to checked, use row id as input id (plus prefix)
return '<label class="switch"><input type="checkbox" ' + ((data == 1) ? 'checked' : '') + ' value="' + row.kwartaal_id + '"
class="active" name="' + columnName + '" /><div class="slider round"><span class="on">ON</span><span class="off">OFF</span></div></label>';
}
return data;
},
You can use the meta object in the column renderer to access a column's data value:
meta.settings.aoColumns[meta.col].mData
This accesses the DataTables settings object which contains an array of column data values. You can get the relevant entry in that array by using meta.col which is the current column's index.
Here is an example:
var dataSet = [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Zürich",
"extn": "5421"
},
{
"id": "57",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
];
$(document).ready(function() {
var table = $('#example').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{
title: "Start date",
data: "start_date",
render: function ( data, type, row, meta ) {
if (type === 'display') {
//console.log( meta.settings.aoColumns[meta.col].mData );
return meta.settings.aoColumns[meta.col].mData;
} else {
return data;
}
}
},
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
]
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
</table>
</div>
</body>
</html>
The demo simply prints the data value in the Start Date column. You can obviously use that value in your name="' + columnName + '" code instead.
Related
I am new to development, and trying to build data table with JSON. So far I did
{
"qty": "2",
"price": 1
}, {
"qty": "3",
"price": "5",
}, {
"qty": "3",
"price": "4",
}
var table = $('#example').DataTable({
data: dataSet,
columns: [{
title: "qty",
data: "qty"
},
{
title: "price",
data: "price",
render: function(data, type, row) {
return '<input type="number" value="' + data + '">';
},
{
title: "total",
data: "multiplication'}
}
]
I want to perform multiplication of two rows qty and price and store result in third row.
Consider another example.
$(function() {
var dataSet = [{
"qty": 2,
"price": 1.00,
},
{
"qty": 3,
"price": 5.99
},
{
"qty": 3,
"price": 4.00
}
];
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
$.each(dataSet, function(i, r) {
r.total = calcTotal(r.qty, r.price);
});
var table = $('#example').DataTable({
data: dataSet,
columns: [{
"data": "qty"
},
{
"data": "price",
"render": function(data, type, row) {
return '$<input type="number" class="price-input" min="0.00" step="0.01" value="' + data + '" />';
}
},
{
"data": "total",
"render": function(data, type, row) {
return "$" + data;
}
}
]
});
$("#example").on("change", ".price-input", function(event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(0)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(2).get(0));
total.data(calcTotal(qty, price)).draw();
});
});
td {
text-align: center !important;
}
.price-input {
width: 5em;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This updates the Data Set before building the Table. So the values are already there. You can then use a change callback to modify that data.
Note: Most interfaces want to change the Quantity and not the price, but since your example changed the Price, I kept it as is. You can easily modify this to work the other way.
Here is a simple solution you can do this with columnDefs option:
In your column definition, add a third data column with the value null. (Remember to have the number of columns matching in your HTML). I created a third HTML column with the <th>Total</th>. The table will render the column empty.
When it gets to the columnDef, you want to make sure you target the correct column, remember it reads them based on a 0 index, so 2 is actually 3.
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return type === 'display' ? ((full.qty)*(full.price)) + '' : data;
}
Remember, the full parameter is the data for the entire row, so in the return of your render, you multiply the two data values (full.qty)*(full.price)
var dataSet = [
{
"qty": "2",
"price": "1",
},
{
"qty": "3",
"price": "5"
},
{
"qty": "3",
"price": "4"
}]
var table = $('#example').DataTable({
data: dataSet,
columns: [
{"data" : "qty"},
{"data": "price"},
{"data" : null}
],
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return "$" + ((full.qty)*(full.price));
}
}]
});
td {
text-align: center !important;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I'm working with Datatable. The problem is I need to get all the values from each row's dropdownlist. The datatable have the column 'Company' which the user need to select value from dropdownlist .Now I'm able to get each row's value for Citizen_ID and Tel using the code below.
var rowData = table.rows().data();
var dataArr = [];
$.each($(rowData), function(key,value){ //data
let tempObj = {
Citizen_id: value["Citizen_ID"],
Tel: value["Tel"]
}
dataArr.push(tempObj);
});
How can I get selected value from dropdownlist for all datatable pages?.
I would approach this in a slightly different way.
Some of the data you need can be accessed from the DataTable, but the selected value in each row's drop-down list only exists in the DOM, so you need the related DOM node to access that data.
I would therefore populate the following two variables, at the start:
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
Both of these are populated using DataTables API calls, so the entire table is processed.
This gives you two arrays - one with the DataTables data objects for each row, and the other with the DOM nodes.
Then you can use a traditional for loop to iterate the arrays in parallel, and extract the specific pieces of data you need.
For the drop-down node, you can use a jQuery selector:
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
I used a class (value = company) in the HTML code for the select, just in case there are multiple different selects in one row.
Here is a demo of the overall approach:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
</table>
<br>
<button id="data_btn" type="button">Get Data</button>
</div>
<script>
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
];
$(document).ready(function() {
var table = $('#example').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Company",
defaultContent: '',
render: function ( data, type, row, meta ) {
if (type === 'display') {
return '<select class="company">'
+ '<option value="Google">Google</option>'
+ '<option value="Microsoft">Microsoft</option>'
+ '<option value="Amazon">Amazon</option></select>';
} else {
return data;
}
}
},
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
]
} );
$("#data_btn").on( "click", function() {
var rowData = table.rows().data().toArray();
var rowNodes = table.rows().nodes().toArray();
var dataArr = [];
for (i = 0; i < rowData.length; i++) {
let selectedCompany = $(rowNodes[i]).find("select.company option:selected").text();
let tempObj = {
id: rowData[i].id,
name: rowData[i].name,
company: selectedCompany
}
dataArr.push(tempObj);
}
console.log( dataArr );
});
} );
</script>
</body>
</html>
When you run the demo, first select a "company" value in each of the drop-downs.
Then click the "Get Data" button.
The resulting object will look similar to the following:
[
{
"id": "123",
"name": "Tiger Nixon",
"company": "Amazon"
},
{
"id": "456",
"name": "Donna Snider",
"company": "Microsoft"
}
]
I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );
Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/
I'm having a issue that I dont know how to afford. I have a kendo grid which is being poblated with a json file.
The issue is that in the json file there is a field that has a different type in different elements.
I'll explain myself with an example:
"listaPreguntas": [
{
"idPregunta": 1126,
"idTipificacion": 1712,
"tipoPregunta": "E",
"pregunta": "¿DE QUE COLOR ES?",
"numeroOrden": 2,
"respuestasPosibles": [
{
"idRespuestaPosible": 1066,
"respuestaPosible": "HOSPITAL"
},
{
"idRespuestaPosible": 1068,
"respuestaPosible": "AMBULATORIO"
},
{
"idRespuestaPosible": 1070,
"respuestaPosible": "CENTRO SALUD"
},
{
"idRespuestaPosible": 1072,
"respuestaPosible": "UNIDAD MOVIL"
},
{
"idRespuestaPosible": 1074,
"respuestaPosible": "UNIDAD DONACION"
},
{
"idRespuestaPosible": 1076,
"respuestaPosible": "UNIDAD MOVIL (UVI)"
}
],
"idTipoEnumerado": 1
},
{
"idPregunta": 1150,
"idTipificacion": 1712,
"tipoPregunta": "T",
"pregunta": "¿cuantas personas?",
"numeroOrden": 1,
"respuestasPosibles": null,
"idTipoEnumerado": 0
},
{
"idPregunta": 1152,
"idTipificacion": 1712,
"tipoPregunta": "F",
"pregunta": "¿Mayores?",
"numeroOrden": 3,
"respuestasPosibles": null,
"idTipoEnumerado": 0
}
You can see three objects in the json file, the first object has a type "E" and has six possible values, the second object has a type "T" (Text) and the last one is a boolean.
What i need is to show in the grid a column which type change depending on the type of the json. I need to have a text value in some cases, a checkbox and a dropdownbox.
I hope you could understand me.
Thanks in advance.
Here is example for custom editor from http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-columns.editor
$("#grid").kendoGrid({
columns: [ {
field: "name",
editor: function(container, options) {
var input = $("<input/>");
input.attr("name", options.field);
input.appendTo(container);
if(options.model.tipoPregunta == 'E')
{
input.kendoDropDownList( ... );
}
if(options.model.tipoPregunta == 'T')
{
....
}
if(options.model.tipoPregunta == 'F')
{
....
}
}
} ],
editable: true,
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" } ]
});
options.model is a row dataItem
You just need to create a template for your column in your grid config:
columns: [{
field: "respuestasPosibles",
template: function(e){
if ( (e.tipoPregunta === 'E') && $.isArray(e.respuestasPosibles) ){
var st = '';
$.each(e.respuestasPosibles, function(i, a){
st += a.respuestaPosible + '(' + a.idRespuestaPosible + ')<br>';
});
return st;
}
else{
// The cell will be empty
return '-';
}
}, ....
]
Consider this JSON
{
"stream": {
"posts": [{
"post_id": "1",
"post_type": "text",
"post_thumb": "bla1",
"comments": [{
"comment_id": "7",
"comment_text": "asd",
},
{
"comment_id": "8",
"comment_text": "sdf",
}],
}],
}
}
and my Model
Ext.define('MyAppApp.model.Post', {
extend: 'Ext.data.Model',
config: {
fields: [
'post_id',
'post_type',
'post_thumb',
'comments',
],
proxy: {
type: 'jsonp',
url: 'http://MyApp.com/home/index_app',
reader: {
type: 'json',
rootProperty: 'stream'
}
}
}
});
The above correctly shows a list of posts in my view.
I added a controller to push a panel to show the full content of each post, which is working.
Controller
Ext.define('MyAppApp.controller.Main', {
extend: 'Ext.app.Controller',
config: {
refs: {
stream: 'homepanel'
},
control: {
'homepanel list': {
itemtap: 'showPost'
}
}
},
showPost: function(list, index, element, record) {
/////// begin code block that solved my problem
var data = record.get('comments');
var comments = '';
Ext.Array.each(data, function(item) {
comments += [item.comment_text] + '<br />';
});
/////// end
this.getStream().push({
xtype: 'panel',
html: [
'<p>' + record.get('post_thumb') + '</p>',
'<p>' + record.get('comments') + '</p>',
comments // added to output HTML
].join(''),
scrollable: true,
styleHtmlContent: true,
});
}
});
My trouble is with retrieving the data from comments, which are nested in the JSON.
With the above controller, I get
[object Object],[object Object]
in my view and in the console I can open those objects and see the entirety of my comments.
But how do I display them in the view? (eg, how do I display "comment_text"?)
Well, they are no longer JSON as soon as they are in your model, they got deserialized to object. To display them you should use a XTemplate. If you already use a template within your view you can directly access the properties of the objects to to render them. Let me know if anything is still unclear.
Why exactly do you render the content by yourself into html property? Is that cause of performance reasons? I am not that used to ST, therefore I ask. Anyway, build up a little helper function that will loop through the comment array and return is as more or less formatted string (this will be up to you, also the check that the array is at least a empty one and never null)
var data = record.get('comments')
function(data) {
var result = '',
len = data.length,
i=0;
for(;i<len;i++) {
result += data[i]['comment_text'] +'<br />'
}
return result;
}
Here is a implementation into the origin function. I post this cause the use of Ext.Array.each is not recommend, because it executes a function for each element and functioncalls within loops should be spared.
showPost: function(list, index, element, record) {
var data = record.get('comments');
function fetchComments(data) {
var result = '',
len = data.length,
i = 0;
for(;i<len;i++) {
result += data[i]['comment_text'] + '<br />';
}
return result;
}
this.getStream().push({
xtype: 'panel',
html: [
'<p>' + record.get('post_thumb') + '</p>',
'<p>' + fetchComments(data) + '</p>'
].join(''),
scrollable: true,
styleHtmlContent: true,
});
}
Here is the other way I have iterated.
Json data:
{
"account" : [
{
"id": "1",
"accNo" : "5869785254",
"curAmt" : "25000",
"balAmt" : "15000",
"transdate" : [
{
"date" : "10",
"month" : "03",
"description" : "Check 232",
"crddbt" : "-1200"
},
{
"date" : "14",
"month" : "03",
"description" : "ATM Withdrawl",
"crddbt" : "-500"
}
],
}
]
}
Sencha Code to iterate on transdate object.
var transDateObj = record.get('transdate');
Ext.Object.each(transDateObj, function(key, value, myself){
Ext.Object.each(value, function(key, value, myself){
console.log(key + ":" + value);
});
});