<!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>