How to get value from each datatable row dropdownlist - javascript

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"
}
]

Related

How to use column name in render function using datatables

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.

jQuery DataTable add dynamic columns

I have a JSON object like below (dataSource) in that JSON object the property 'viewClasses' sometimes comes as blank, here what I want to do is if 'viewClasses' have any record I want to add a dynamic column to the table and the name of the column header will be the value of 'viewClasses.class', I have tried the below code but it's not working as expected.
Here is the result of the below code -
Here how I want this to be-
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var column = [];
function AddColumn() {
$.each(dataSource[0].viewDetails.viewClasses[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
column.push(my_item);
});
}
$('#example').dataTable({
data: dataSource[0].viewDetails.viewClasses,
"columns": column,
"paging": false,
"bInfo": false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<style src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="example" class="table table-striped" width="100%"></table>
</div>
</div>
</div>
Your source data needs to be iterated in two different ways, to build the two different dynamic arrays which DataTables needs: - column data and row data.
Firstly you have two columns, A and B. To build the array for these, you can use the following:
var dynamicColumns = [];
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
});
I chose not to use the jQuery iterator because I want access to each object in the array.
This gives me the following structure:
[
{
"data": "A",
"title": "Heading A"
},
{
"data": "B",
"title": "Heading B"
}
]
But for the table's data, I want to end up with only one row of data:
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
Here, I end up with the following:
[
{
"A": 2000,
"B": 3000
}
]
Now I have the structures I need for my DataTable initialization. The overall script therefore is as follows:
<script type="text/javascript">
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var dynamicColumns = [];
var dynamicRows = [];
function buildDynamicData() {
var columnData = dataSource[0].viewDetails.viewClasses;
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
}
buildDynamicData();
console.log(dynamicColumns);
console.log(dynamicRows);
$(document).ready(function() {
$('#example').DataTable({
columns: dynamicColumns,
data: dynamicRows,
paging: false,
info: false
});
} );
</script>
And the end result looks like this (in my test environment):

Loop fetches all the words in 1 input field

as you can see in the picture below, my words 'es' and 'presso' are put into one input field instead of 'es' in one and 'presso' in another input field.
how my JSON looks like:
{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how my loop looks like:
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
});
to zoom in on the loop where I fetch the syllables:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
the function where I create the syllable inputs:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
what is it that I am doing wrong? (I did declare the variable SyllablesID so don't worry about that part).
var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
};
function draw(data){
for (ex of data.main_object.main_object.exercises){
for( sy of ex.syllables){
$("#container").append(`<input type="text" value="${sy}">`)
}
}
}
draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>
syllables is an array as per to posted JSON so you'll have to get each value and add it as a value to the input element. You can again use .map or for/forEach etc to loop through syllabus array and add the array entries to input values
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$.map(exer.syllables, function(syll, i){
$(".syllable" + i).val(syll);
})
});

How click to open popup Organisational Chart Plugin With jQuery

this is tree view on my website based on jquery org chart plugin, this tree created dynamically and also create children.
code is :
$(function() {
var datascource = {
'name': 'Kirby Cochran',
'title': '5061',
'children': [
{
"name": "Sharon Edwards",
"title": "11454",
"children": [
{
"name": "Kirby Cochran",
"title": "5061-kr",
"children": [
{
"name": "Michael Wach",
"title": "5063"
}
]
},
{
"name": "Phil Ungricht",
"title": "6189",
"children": [
{
"name": "Elaine 2 Cochran",
"title": "10238"
}
]
},
{
"name": "Roberto Montero",
"title": "5371"
}
]}]};
var oc = $('#chart-container').orgchart({
'data' : datascource,
'nodeContent': 'title',
'draggable': true,
'dropCriteria': function($draggedNode, $dragZone, $dropZone) {
if($draggedNode.find('.content').text().indexOf('manager') > -1 && $dropZone.find('.content').text().indexOf('engineer') > -1) {
return false;
}
return true;
}
});
oc.$chart.on('nodedropped.orgchart', function(event) {
console.log('draggedNode:' + event.draggedNode.children('.title').text()
+ ', dragZone:' + event.dragZone.children('.title').text()
+ ', dropZone:' + event.dropZone.children('.title').text()
);
});});
here requirement is if clicked any boxes open the popup and show details of customers. org chart
Here is some code snippet to load a pop-up
$(.node).click(function(){
var id = $(this).attr('id');
// use ajax here and getdata using id then display a modal and populate it
});

Javascript Datatables generating HTML link using render function on JSON data

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/

Categories

Resources