I am using a data table similar as.
$(document).ready(function() {
var table = $("#example").DataTable({
"order": [ 1, "asc" ],
// "lengthMenu": [[ 100, 200, 500,-1], [ 100, 200, 500,'All']],
"pageLength": -1,
"lengthChange": false,
"bFilter": "false",
"searchable": false,
orderCellsTop: true,
"bPaginate": false,
"bInfo": false
});
$('.filterRow th').each( function (i) {
var title = $(this).text();
var select = $('<select><option value="">All</option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var term = $(this).val();
table.column( i ).search(term, false, false ).draw();
} );
let includedArr = [];
let colData = table.column( i ).data().unique().sort().each( function ( d, j ) {
if(d != ""){
d = d.replace("<del>","").replace("</del>","");
if( $.inArray(d, includedArr) < 0 ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
includedArr.push = d;
}
}
});
} );
} );
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<table id="example" class="display" style="width:100%">
<tbody>
<tr>
<td>N</td>
<td>101</td>
<td>1</td>
<td>01</td>
<td>10</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>102</td>
<td>1</td>
<td>02</td>
<td>(20)</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>103</td>
<td>1</td>
<td>03</td>
<td>
<del>10</del>
</td>
<td>20</td>
</tr>
</tbody>
<thead>
<tr>
<th rowspan="2">Bldg</th>
<th rowspan="2">Unit</th>
<th rowspan="2">Floor</th>
<th rowspan="2">Stack</th>
<th colspan="2">
Floor Level
</th>
</tr>
<tr>
<th>Floor 1</th>
<th>Floor 2</th>
</tr>
<tr class="filterRow">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
You can run the code and check on the select option of Floor 1 column, currently there it is showing double 10 option. But, it should have only one. Actually, there are this two options: 10 and '10'. Because of this del tag it considered as two options, however, I want to show just 10.
So, I tried by removing <del> tag but still, it is showing 3 options on the select field.
Related
I am working on a datatable where I need to limit the search to one column only when using paramater.
example:abc.com?search=test. But, if not passing parameter, it should search all columns. How do I achieve this? Here is the code I have.
Here is the fiddle: http://live.datatables.net/piquxewa/1/edit
Javascript
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
$(document).ready(function() {
var searchTerm = getUrlVars()['search'];
var table = $('#example1').DataTable( {
responsive: true,
paging: false,
searching: true,
lengthChange: false,
bInfo: false,
bSort: true,
"columnDefs": [
{ "searchable": false, "targets": 0 }
],
search: {
search: searchTerm
}
});
});
</script>
HTML:
<h2>Datatable 2</h2>
<table id="example1" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;"><thead>
<tr role="row">
<th style=" width: 11%;">Date</th>
<th style=" width: 23%;">Name</th>
<th style=" width: 23%;">Type</th>
<th style=" width: 23%;">Topic</th>
<th style=" width: 20%;">Hidden</th>
</tr>
</thead><tbody>
<tr>
<td>Current</td>
<td>John Doe</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>
<tr>
<td>Current</td>
<td>Baby</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>
<tr>
<td>Current</td>
<td>Joe</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>
<tr>
<td>Current</td>
<td>John</td>
<td>ABC</td>
<td>Test</td>
<td>orange, banana</td>
</tr>
</tbody></table>
</div>
</html>
If I understood well, you want the searchable option to be set to true for column 0 ONLY IF exists a search term for the search= GET parameter, right?
Otherwise, you want to set it to false.
That's how you can achieve it with a ternary operator:
"columnDefs": [
{ "searchable": searchTerm === undefined ? false : true, "targets": 0 }
],
I want to have a DataTable with a sticky header where I can filter with selects the columns. I want to have the select inputs as sticky header, so it needs to be on the second header column. This is why I have modified the standard code from the DataTables documentation.
This is how it should be by documentation:
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
I have changed it to:
var select = $('<select><option value=""></option></select>')
.appendTo( $('#contact_overview_table thead tr:eq(1) th').empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
However, now the select option values are wrong... How can I fix this?
Here you can find a working demo which I found while I was searching for a solution. Except the select inputs aren't sticky..
http://live.datatables.net/hepeqiro/55/edit
My code so far:
var table;
var groupColumn = 1;
$(document).ready(function() {
table = $('#contact_overview_table').DataTable( {
"displayStart": 0,
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.19/i18n/German.json"
},
"columnDefs": [
{ "visible": false, "targets": groupColumn }
],
"order": [[ groupColumn, 'asc' ]],
"processing": true,
"pageLength": 100,
orderCellsTop: true,
fixedHeader: true,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(groupColumn, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="15" style="font-weight: bold;">'+group+'</td></tr>'
);
last = group;
}
} );
},
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $('#contact_overview_table thead tr:eq(1) th').empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
});
// Order by the grouping
$('#contact_overview_table tbody').on( 'click', 'tr.group', function () {
var currentOrder = table.order()[0];
if ( currentOrder[0] === groupColumn && currentOrder[1] === 'asc' ) {
table.order( [ groupColumn, 'desc' ] ).draw();
}
else {
table.order( [ groupColumn, 'asc' ] ).draw();
}
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js"></script>
<link href="https://cdn.datatables.net/fixedheader/3.1.5/css/fixedHeader.bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="contact_overview_table_div" class="table-responsive">
<table class="table table-striped table-bordered" id="contact_overview_table">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Art</th>
<th class="text-center">Anrede</th>
<th class="text-center">Titel</th>
<th class="text-center">Vorname</th>
<th class="text-center">Name</th>
<th class="text-center">Firma</th>
<th class="text-center">Straße</th>
<th class="text-center">Ort</th>
<th class="text-center">Mobil</th>
<th class="text-center">Actions</th>
</tr>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Art</th>
<th class="text-center">Anrede</th>
<th class="text-center">Titel</th>
<th class="text-center">Vorname</th>
<th class="text-center">Name</th>
<th class="text-center">Firma</th>
<th class="text-center">Straße</th>
<th class="text-center">Ort</th>
<th class="text-center">Mobil</th>
<th class="text-center tfoot-hide-select">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<th>Customer</th>
<th></th>
<th>Porf</th>
<th>Max</th>
<th>Müller</th>
<th></th>
<th></th>
<th>Berlin</th>
<th>+21 431 8912</th>
<th class="text-center">Actions</th>
</tr>
<tr>
<th>2</th>
<th>Customer</th>
<th></th>
<th></th>
<th>Tim</th>
<th>See</th>
<th></th>
<th></th>
<th>Stockholm</th>
<th>+44 123 5763</th>
<th class="text-center">Actions</th>
</tr>
<tr>
<th>1</th>
<th>Supplier</th>
<th></th>
<th>Dr</th>
<th>Philipp</th>
<th></th>
<th></th>
<th></th>
<th>New York</th>
<th>+49 241 4513</th>
<th class="text-center">Actions</th>
</tr>
<tr>
<th>2</th>
<th>Supplier</th>
<th></th>
<th></th>
<th>Max</th>
<th>Hue</th>
<th></th>
<th></th>
<th>Los Angelas</th>
<th>+44 124 1341</th>
<th class="text-center">Actions</th>
</tr>
</tbody>
</table>
</div>
Kind regards and Thank you!
initComplete: function () {
this.api().columns().every( function (z) {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $('#contact_overview_table thead tr:eq(1) th:eq('+z+')').empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>')
} );
} );
},
I have a chart that gets the data values from a table column. It currently works on its own, but I want to add a functionality that changes/updates the data of the chart on button click. I tried this code but it doesn't work (arrays are very confusing for me):
var canvasP = document.getElementById("pieChart");
var table = document.getElementById("myTable");
var nameArr = [];
var data1Arr = [];
var data2Arr = [];
var tableLen = table.rows.length;
var i;
for (i = 1; i < tableLen; i++) {
nameArr.push(table.rows[i].cells[0].textContent);
data1Arr.push(table.rows[i].cells[1].innerHTML);
data2Arr.push(table.rows[i].cells[2].innerHTML);
}
nameArr.pop();
data1Arr.pop();
data2Arr.pop();
var ctxP = canvasP.getContext("2d");
var myPieChart = new Chart(ctxP, {
type: "pie",
data: {
labels: nameArr,
datasets: [{
data: data1Arr,
backgroundColor: ["#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1", "#64B5F6", "#FFD54F", "#2196F3", "#FFC107", "#1976D2", "#FFA000", "#0D47A1"],
label: "Data"
}]
},
options: {
legend: {
display: true,
position: "right"
},
title: {
display: true,
text: "Data 1"
}
}
});
// the button functions below do not work. I am trying to load the array variables into the data:
document.getElementById("btn1").addEventListener("click", function() {
myPieChart.data.datasets.data = data1Arr;
});
document.getElementById("btn2").addEventListener("click", function() {
myPieChart.data.datasets.data = data2Arr;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<table id='myTable'>
<thead>
<tr>
<th>Name</th>
<th>1st data</th>
<th>2nd data</th>
</tr>
</thead>
<tbody>
<tr>
<th>Item 1</th>
<td>337</td>
<td>411</td>
</tr>
<tr>
<th>Item 2</th>
<td>290</td>
<td>110</td>
</tr>
<tr>
<th>Item 3</th>
<td>197</td>
<td>800</td>
</tr>
<tr>
<th>Item 4</th>
<td>765</td>
<td>211</td>
</tr>
<tr>
<th>Item 5</th>
<td>331</td>
<td>451</td>
</tr>
<tr>
<th>Item 6</th>
<td>957</td>
<td>871</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td id='curPop'>2877</td>
<td>2854</td>
</tr>
</tfoot>
</table>
<canvas id='pieChart'></canvas>
<button id="btn1">
Data 1
</button>
<button id="btn2">
Data 2
</button>
What I would want is that when the Data 2 button is clicked, it loads the appropriate data from the table (2nd data) into the pie chart, and that the Data 1 button loads the 1st data of the table.
After testing several times, this seems to fix the issue:
document.getElementById("btn1").addEventListener("click",function(){
myPieChart.data.datasets[0].data = data1Arr;
myPieChart.update();
});
document.getElementById("btn2").addEventListener("click",function(){
myPieChart.data.datasets[0].data = data2Arr;
myPieChart.update();
});
I want to allow the user to reorder the columns in the table by dragging and dropping them. I am using jquery.dragtable.js to allow drag and drop. It`s working fine. Now I want to store the table order after drag and drop on the client-side and restore the state onload.
Here is my HTML Code:
<table id="tblReg" class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td>545trt574</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td>yffft5456</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td>fgfhgf444</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>4</th>
<td>Rima</td>
<td>the Bird</td>
<td>#twitter</td>
<td>jjk8899</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>5</th>
<td>Sundar</td>
<td>the Bird</td>
<td>#twitter</td>
<td>76767687hjh</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
</tbody>
</table>
Get Table Order
<p class="porder"></p>
Jquery:
$(document).ready(function(){
$('#tblReg').each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not( .notdraggable ):not( :has( .dragtable-drag-handle ) ), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
});
});
$('a.order').click(function(){
console.log($('#tblReg').dragtable('order'));
var curOrder = $('#tblReg').dragtable('order');
$('.porder').text(curOrder);
return false;
});
});
Plugin Refer: https://github.com/akottr/dragtable
The allow to provide get the table order as follows:
["#", "First Name", "Last Name", "Username", "Password", "Email", "Phone"]
Now I want to store this in client side (LocalStorage / Cookies) and reorder OnLoad as per save data.
How to do this? I'm new in jquery.
Try this code, Its working fine.
Columns ordering set into sessionStorage after drag-n-drop and then refresh your page. You will see columns order change.
Ordering records in array format, You can see in console:
<!DOCTYPE html>
<html>
<head>
<title>Reorder</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//rawgithub.com/akottr/dragtable/master/dragtable.css" />
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<table id="tblReg" class="table table-bordered">
<thead>
<tr class="active">
<th id="number">#</th>
<th id="fname">First Name</th>
<th id="lname">Last Name</th>
<th id="uname">Username</th>
<th id="pass">Password</th>
<th id="email">Email</th>
<th id="phone">Phone</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td>545trt574</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td>yffft5456</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td>fgfhgf444</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>4</th>
<td>Rima</td>
<td>the Bird</td>
<td>#twitter</td>
<td>jjk8899</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
<tr>
<th>5</th>
<td>Sundar</td>
<td>the Bird</td>
<td>#twitter</td>
<td>76767687hjh</td>
<td>Na#email.com</td>
<td>7788994320</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-12">
Get Table Order
<p class="porder"></p>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="//rawgithub.com/akottr/dragtable/master/jquery.dragtable.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// this code for sessionStorage
$('#tblReg').dragtable({
persistState: function(table) {
if (!window.sessionStorage) return;
var ss = window.sessionStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('tableorder', JSON.stringify(table.sortOrder));
},
restoreState: eval('(' + window.sessionStorage.getItem('tableorder') + ')')
});
// this code for each th drag and drop
$('#tblReg').each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
});
});
// Click and then you see ordering of (th) in console.
$('a.order').click(function(e){
e.preventDefault();
var order_array = [];
$('#tblReg').dragtable().find('thead th').each(function(i,v){
order_array.push($(v).text());
});
console.log(order_array);
$('.porder').text(order_array);
});
});
</script>
</body>
</html>
Try this code for columns order store in localStorage.
//For localstorage
$('#tblReg').dragtable({
persistState: function(table) {
if (!window.localStorage) return;
var ss = window.localStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('tableorder', JSON.stringify(table.sortOrder));
$('a.order').trigger('click');//When drop the column then button will trigger
},
restoreState: eval('(' + window.localStorage.getItem('tableorder') + ')')
});
I have done ! Please check if any mistake.
$(document).ready(function(){
//localStorage.clear();
var tblReg = $('#tblReg').attr('id');
var tblRegMaster = $('#tblRegMaster').attr('id');
processDnD(tblReg);
processDnD(tblRegMaster);
});
function processDnD(cuTable){
var tblName = cuTable;
$('#'+cuTable).find('th').each(function() {
var ctxt = $(this).text();
if(ctxt == 'First Name'){
$(this).attr('id','firstName-'+tblName);
}else if(ctxt == 'Password'){
$(this).attr('id','password'+tblName);
}else if(ctxt == 'Email'){
$(this).attr('id','iemail'+tblName);
}else if(ctxt == 'Username'){
$(this).attr('id','userName'+tblName);
}else if(ctxt == 'Last Name'){
$(this).attr('id','lastName'+tblName);
}else if(ctxt == '#'){
$(this).attr('id','slNo'+tblName);
}else if(ctxt == 'Phone'){
$(this).attr('id','phone'+tblName);
}else if(ctxt == 'PO Number'){
$(this).attr('id','pono'+tblName);
}else if(ctxt == 'Shipper'){
$(this).attr('id','shipperName'+tblName);
}else if(ctxt == 'Status'){
$(this).attr('id','cuStatus'+tblName);
}else if(ctxt == 'Booking Line'){
$(this).attr('id','BookingLine'+tblName);
}else if(ctxt == 'Access Mode'){
$(this).attr('id','AccessMode'+tblName);
}else if(ctxt == 'Container No'){
$(this).attr('id','ContainerNo'+tblName);
}
})
$('#'+cuTable).dragtable({
persistState: function(table) {
if (!window.localStorage) return;
var ss = window.localStorage;
table.el.find('th').each(function(i) {
if(this.id != '') {table.sortOrder[this.id]=i;}
});
ss.setItem('setTableOrder-'+tblName, JSON.stringify(table.sortOrder));
},
restoreState: eval('(' + window.localStorage.getItem('setTableOrder-'+tblName) + ')')
});
$('#'+cuTable).each(function(){
$(this).dragtable({
placeholder: 'dragtable-col-placeholder',
items: 'thead th:not(.notdraggable):not(:has(.dragtable-drag-handle)), .dragtable-drag-handle',
appendTarget: $(this).parent(),
scroll: true
})
});
}
I've got a table with 5 rows and two columns. Each row, has an ID column, ranging from 1-5.
I want to add JSON data to that said table, IF, that data has a matching ID to that row. If NO data matches that rows ID, add "No Matching Record" to that rows second column.
HTML Table
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
Json Data
{"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]}
Expected Result
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Doe</td>
</tr>
<tr>
<td>2</td>
<td>No Matching Record</td>
</tr>
<tr>
<td>3</td>
<td>Jones</td>
</tr>
<tr>
<td>4</td>
<td>No Matching Record</td>
</tr>
<tr>
<td>5</td>
<td>No Matching Record</td>
</tr>
</tbody>
</table>
You can do this with .each() to loop each tr and then use find() to get object from data that has same id as text in td.
//Loop each row or tr
$('tbody tr').each(function() {
//Get text or number from each first td in every row
var i = $(this).find('td:first').text();
//Find object from data with this id or current id of td
var r = data.data.find((e) => e.id == i);
//Select second td from current row
var t = $(this).find('td:eq(1)');
//If Object is found with current id add lastName as text else add dummy text or No Matching Record
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});
var data = {"data":[{"id":"1", "lastName":"Doe"},{"id":"3", "lastName":"Jones"}]}
$('tbody tr').each(function() {
var i = $(this).find('td:first').text();
var r = data.data.find((e) => e.id == i);
var t = $(this).find('td:eq(1)');
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
If you want to filter by index of rows instead of text from td you can just use $(this).index() + 1; and the rest is same
var data = {
"data": [{
"id": "1",
"lastName": "Doe"
}, {
"id": "3",
"lastName": "Jones"
}, ]
}
//Loop each row or tr
$('tbody tr').each(function() {
//Get index of row
var i = $(this).index() + 1;
//Find object from data with this id or current id of td
var r = data.data.find((e) => e.id == i);
//Select second td from current row
var t = $(this).find('td:eq(1)');
//If Object is found with current id add lastName as text else add dummy text or No Matching Record
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
First, add classes to the two types of td's for convenience. Then following code should work. Here I am iterating through all rows in tbody and then searching through the json if any matching value is found. If no matching value is found, default value ("No data found") is put in the lastName column.
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td class="id">1</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">2</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">3</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">4</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">5</td>
<td class="name"></td>
</tr>
</tbody>
</table>
var json = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
$(".table tbody tr").each(function(index){
var curId = $(this).find(".id").text();
var nameField = "No data found";
for( var i = 0; i < json.data.length; i++ )
{
var row = json.data[i];
if( row.id == curId )
{
nameField = row.lastName;
return false;
}
}
$(this).find(".name").text( nameField );
});//each
The following code would do the trick:
var response = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
var myData = response.data;
var rows = $('#myDataTable tbody tr');
var cells, index, itemFound = false;
rows.each(function (index) {
cells = $(this).find('td');
itemFound = false
for (index=myData.length-1 ; index>= 0 && !itemFound; index--) {
if (cells.eq(0).text() == myData[index].id) {
itemFound = true;
cells.eq(1).text(myData[index].lastName);
myData.splice(index, 1);
}
}
if (!itemFound) {
cells.eq(1).text('No matching record');
}
});
See my working js fiddle:
https://jsfiddle.net/gkptnnxe/
If you don't want to add class or id's to your td's then you can use this.
var obj = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
var trs = document.getElementsByTagName("tr");
// don't need for i==0
for(var i=1; i<trs.length; i++){
var tds = trs[i].children;
var id = tds[0].innerHTML;
var nameFound = false;
//search this id in json.
var len = obj.data.length;
for(var j=0; j<obj.data.length; j++){
if(obj.data[j].id == id){
// If found then change the value of this lastName cell.
tds[1].innerHTML = obj.data[j].lastName;
nameFound = true;
}
}
// If id is not found is json then set the default message.
if(nameFound == false){
tds[1].innerHTML = "No mathcing records";
}
}
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
You can get td by index and check the text of td if it matches add name to next td
var data = {
"data": [
{ "id": "1", "lastName": "Doe" },
{ "id": "3", "lastName": "Jones" }
]
};
$(".table-striped tbody tr").each(function(){
var index = data.data.map(function (e) { return e.id }).indexOf($(this).first().text().trim());
if(index > -1)
$(this).children('td:eq(1)').text(data.data[index].lastName);
else
$(this).children('td:eq(1)').text('No matching record');
});