I have a html table that i want to convert into json format but i'm not getting correctly.
the resultant json is not coming according to my format
here is my table
<table class="table" id="example-table">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="allTheQuotationRow">
<td>flex board</td>
<td contenteditable="" class="priceChangeField">3</td>
<td contenteditable="" class="quantityChangeField">5</td>
<td>15</td>
</tr>
<tr class="allTheQuotationRow">
<td>sign board</td>
<td contenteditable="" class="priceChangeField">20</td>
<td contenteditable="" class="quantityChangeField">1</td>
<td>20</td>
</tr>
<tr class="allTheQuotationRow">
<td>flex board</td>
<td contenteditable="" class="priceChangeField">30</td>
<td contenteditable="" class="quantityChangeField">1</td>
<td>30</td>
</tr>
<tr class="allTheQuotationRow">
<td>sign board</td>
<td contenteditable="" class="priceChangeField">200</td>
<td contenteditable="" class="quantityChangeField">19</td>
<td>3800</td>
</tr>
<tr id="lastTotalRow">
<td>total</td>
<td></td>
<td></td>
<td>3865</td>
</tr>
</tbody>
</table>
i want my desired result to be like this:
{
"flex_board": [
{
"Price": 3,
"Quantity": 5,
"Amount": 15
},
{
"Price": 30,
"Quantity": 1,
"Amount": 30
}
],
"sign_board": [
{
"Price": 20,
"Quantity": 1,
"Amount": 20
},
{
"Price": 200,
"Quantity": 19,
"Amount": 3800
}
],
"total": [
{
"Price": null,
"Quantity": null,
"Amount": 3865
}
]
}
here is my jsfiddle:http://jsfiddle.net/eabangalore/cCzqn/1601/
Please help me thanks in advance!!!
Use querySelectorAll and Array.from to iterate the rows (Comments inline)
var allRows = Array.from( document.querySelectorAll( "tbody tr:not(:last-child)" ) ); //get all rows except last one
var map = {};
allRows.forEach( function( row ){
var cells = row.children;
var prodName = cells[0].innerText; //index by product name
map[ prodName ] = map[ prodName ] || []; //initialize inner array
map[ prodName ].push({ //push each row to the respective product name's index
Price : cells[1].innerText,
Quantity : cells[2].innerText,
Amount : cells[3].innerText
});
});
console.log( map );
Demo
var allRows = Array.from( document.querySelectorAll( "tbody tr:not(:last-child)" ) ); //get all rows except last one
var map = {};
allRows.forEach( function( row ){
var cells = row.children;
var prodName = cells[0].innerText; //index by product name
map[ prodName ] = map[ prodName ] || []; //initialize inner array
map[ prodName ].push({ //push each row to the respective product name's index
Price : cells[1].innerText,
Quantity : cells[2].innerText,
Amount : cells[3].innerText
});
});
console.log( map );
<table class="table" id="example-table">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="allTheQuotationRow">
<td>flex board</td>
<td contenteditable="" class="priceChangeField">3</td>
<td contenteditable="" class="quantityChangeField">5</td>
<td>15</td>
</tr>
<tr class="allTheQuotationRow">
<td>sign board</td>
<td contenteditable="" class="priceChangeField">20</td>
<td contenteditable="" class="quantityChangeField">1</td>
<td>20</td>
</tr>
<tr class="allTheQuotationRow">
<td>flex board</td>
<td contenteditable="" class="priceChangeField">30</td>
<td contenteditable="" class="quantityChangeField">1</td>
<td>30</td>
</tr>
<tr class="allTheQuotationRow">
<td>sign board</td>
<td contenteditable="" class="priceChangeField">200</td>
<td contenteditable="" class="quantityChangeField">19</td>
<td>3800</td>
</tr>
<tr id="lastTotalRow">
<td>total</td>
<td></td>
<td></td>
<td>3865</td>
</tr>
</tbody>
</table>
Refactoring an array like that can be a complicated procedure, but thankfully there is a library called lodash that has a function called groupBy. It can fix your problem in a single line of code!
_.groupBy(table, "Product Name")
That's really it!
Lodash Library
http://jsfiddle.net/nhc6m1af/
You can use reduce to convert your Array into desired Object
$('#convert-table').click(function() {
var table = $('#example-table').tableToJSON();
var result = table.reduce(function(acc, item) {
var key = item["Product Name"].replace(/ /g, "_");
if (!acc[key]) {
acc[key] = []
}
acc[key].push({
Price: item.Price,
Quantity: item.Quantity,
Amount: item.Amount
})
return acc;
}, {});
console.log(result);
});
jsFiddle Link : http://jsfiddle.net/scorpy2007/cCzqn/1603/
You can use same tableToJSON data object in generating your customized format as shown below
var jsondata={};
table.forEach( function( data ){
var prodName = data["Product Name"];
jsondata[ prodName ] = jsondata[ prodName ] ?jsondata[ prodName ]: [];
jsondata[ prodName ].push({
Price : data['Price'],
Quantity : data['Quantity'],
Amount : data['Amount']
});
});
console.log(JSON.stringify(jsondata));
Working fiddle here
Related
I have the next HTML code:
<table border="1">
<tr>
<th>Nº</th>
<th>NOMBRE</th>
<th>AREA</th>
</tr>
<tbody id="curso">
<tr>
<td>1</td>
<td>Jose</td>
<td>Gramática</td>
</tr>
<tr>
<td>2</td>
<td>Luis</td>
<td>Gramática</td>
</tr>
<tr>
<td>3</td>
<td>Andrea</td>
<td>Gramática</td>
</tr>
<tr>
<td>4</td>
<td>Andrea</td>
<td>Idiomas</td>
</tr>
</tbody>
</table>
<p id="Cantidad"></p>
</body>
This code can count the number of rows using a criteria in the AREA field:
<script>
function ContarFila() {
var cantidadFilas = document.getElementById("curso").rows.length;
let resultados = {};
let elementos = document.querySelectorAll(
"table tbody tr > td:nth-child(3)"
);
elementos.forEach(elemento => {
if (resultados.hasOwnProperty(elemento.innerText)) {
resultados[elemento.innerText]++;
} else {
resultados[elemento.innerText] = 1;
}
});
console.log(resultados);
for (let indice in resultados) {
document.getElementById("Cantidad").innerHTML =
resultados['Gramática'];
};
}
window.onload=ContarFila();
</script>
When loading the page and using the 'Gramática' criteria of the 'AREA' field, the result is 3.
How do I include MULTIPLE CRITERIA with the 'NOMBRE' and 'AREA' field at the same time?
Example:
Using Criteria 1: 'Grammar'
Using Criteria 2: 'Luis'
RESULT: 1
THAK YOU!
If I understood you correctly, then perhaps this example below can help you:
function getResult(table, search = {}) {
const tableHeadCells = Array.from(table.tHead.rows[0].cells);
const tableBodyRows = Array.from(table.tBodies[0].rows);
const indexes = tableHeadCells.map((el) => el.dataset["label"]); // <= // ['index', 'nombre', 'area']
const count = tableBodyRows.reduce((acc, row) => {
isSearched = indexes.every(
(key, i) => !search[key] || search[key] === row.cells[i].innerText
);
return isSearched ? ++acc : acc;
}, 0);
return count;
}
const table = document.querySelector('table');
console.log('1 => ', getResult(table, {
area: 'Gramática'
}));
console.log('2 => ', getResult(table, {
nombre: 'Luis',
area: 'Gramática'
}));
console.log('3 => ', getResult(table, {
index: '3',
nombre: 'Andrea'
}));
<table border="1">
<thead>
<tr>
<th data-label="index">Nº</th>
<th data-label="nombre">NOMBRE</th>
<th data-label="area">AREA</th>
</tr>
</thead>
<tbody id="curso">
<tr>
<td>1</td>
<td>Jose</td>
<td>Gramática</td>
</tr>
<tr>
<td>2</td>
<td>Luis</td>
<td>Gramática</td>
</tr>
<tr>
<td>3</td>
<td>Andrea</td>
<td>Gramática</td>
</tr>
<tr>
<td>4</td>
<td>Andrea</td>
<td>Idiomas</td>
</tr>
</tbody>
</table>
Note that in the header of the table, the columns are indicated by data-attributes data-label in order to understand which column belongs to which keyword. And then, we just count the number of elements in the loop, which completely match the specified requirements for all columns
Using Datatables 1.10.19 and bootstrap-datepicker v1.8.0
I have two columns in my table, one contains a cash value, the other contains payment type (cash / card). What I need to do is calculate the totals for each payment type whenever the data is filtered via the datepicker.
So, when a date range is selected I need to display;
Total Cash: £x
Total Card £x
I'm already able to calculate the totals within the table, and when it's filtered via the search input, but i'm stuck on the datepicker.
I have created a fiddle here. Code is below;
html
<div class="container">
<div class="col-md-4 pull-right">
<div class="input-group input-daterange">
<input class="form-control date-range-filter" data-date-format="dd-mm-yyyy" id="min-date" placeholder="From:" type="text">
<div class="input-group-addon">
to
</div><input class="form-control date-range-filter" data-date-format="dd-mm-yyyy" id="max-date" placeholder="To:" type="text">
</div>
</div>
</div>
<hr>
<p>Overall Totals: <span id="overallTotals"></span></p>
<p>Filtered Totals: <span id="filteredTotals"></span></p>
<hr>
<table class="table table-striped table-bordered" id="records" style="width:100%">
<thead>
<tr>
<th>Date Paid</th>
<th>Invoice</th>
<th>Amount</th>
<th>Charge Type</th>
<th>Payment Type</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<tr class="odd" role="row">
<td class="sorting_1">27-03-2019</td>
<td>521735</td>
<td>0.20</td>
<td>overdue</td>
<td>Card</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">27-03-2019</td>
<td>513938</td>
<td>1.20</td>
<td>overdue</td>
<td>Cash</td>
</tr>
<tr class="odd" role="row">
<td class="sorting_1">27-03-2019</td>
<td>523693</td>
<td>0.20</td>
<td>overdue</td>
<td>Cash</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">27-03-2019</td>
<td>493645</td>
<td>0.10</td>
<td>overdue renewed</td>
<td>Cash</td>
</tr>
<tr class="odd" role="row">
<td class="sorting_1">27-03-2019</td>
<td>521734</td>
<td>0.20</td>
<td>overdue</td>
<td>Card</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">27-03-2019</td>
<td>493646</td>
<td>0.10</td>
<td>overdue renewed</td>
<td>Cash</td>
</tr>
<tr class="odd" role="row">
<td class="sorting_1">27-03-2019</td>
<td>523691</td>
<td>0.10</td>
<td>overdue renewed</td>
<td>Card</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">27-03-2019</td>
<td>523692</td>
<td>0.10</td>
<td>overdue renewed</td>
<td>Card</td>
</tr>
<tr class="odd" role="row">
<td class="sorting_1">27-03-2019</td>
<td>523694</td>
<td>0.20</td>
<td>overdue</td>
<td>Cash</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">26-03-2019</td>
<td>506326</td>
<td>1.20</td>
<td>overdue</td>
<td>Card</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">26-03-2019</td>
<td>506322</td>
<td>1.60</td>
<td>overdue</td>
<td>Card</td>
</tr>
<tr class="even" role="row">
<td class="sorting_1">25-03-2019</td>
<td>506399</td>
<td>5.20</td>
<td>overdue</td>
<td>Card</td>
</tr>
</tbody>
</table>
js
$(document).ready(function() {
// Bootstrap datepicker
$('.input-daterange input').each(function() {
$(this).datepicker('clearDates');
});
var table = $('#records').DataTable({
"order": [
[0, "desc"]
],
"columns": [{
data: 'datePaid',
}, {
data: 'invoice',
}, {
data: 'amount',
"render": function(data, type, row) {
return '£' + Number(data).toFixed(2);
},
}, {
data: 'chargeType'
}, {
data: 'paymentType'
}, ],
"columnDefs": [{
targets: [0],
type: 'date-eu'
}],
"footerCallback": function(row, data, start, end, display) {
var api = this.api(),
data;
// Remove the formatting to get integer data for summation
var intVal = function(i) {
return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
};
// find column named Amount
var costColumnIndex = $('th').filter(function(i) {
return $(this).text() == 'Amount';
}).first().index();
// array of total column values
var totalData = api.column(costColumnIndex).data();
// total of column values
var total = totalData.reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0).toFixed(2);
// array of displayed column values
var pageTotalData = api.column(costColumnIndex, {
page: 'current'
}).data();
// total of displayed values
var pageTotal = pageTotalData.reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0).toFixed(2);
// array of displayed column values
var searchTotalData = api.column(costColumnIndex, {
'filter': 'applied'
}).data();
// total of displayed values
var searchTotal = searchTotalData.reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0).toFixed(2);
// console.log(searchTotal);
$('#overallTotals').html('Approximate page total £' + pageTotal + ', search total £' + searchTotal + ', totally total $' + total);
$('#filteredTotals').html('Cash total £' + 'x' + ', Card total £' + 'x');
$(api.column(2).footer()).html('£' + Number(pageTotal).toFixed(2));
},
});
// Extend dataTables search
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
var min = $('#min-date').val();
var max = $('#max-date').val();
var createdAt = data[0] || 0; // Our date column in the table
createdAt = moment(createdAt, "DD-MM-YYYY").format('MM/DD/YYYY');
min = min ? moment(min, "DD-MM-YYYY").format('MM/DD/YYYY') : "";
max = max ? moment(max, "DD-MM-YYYY").format('MM/DD/YYYY') : "";
if (
(min == "" || max == "") || (moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max))) {
return true;
}
return false;
});
// Re-draw the table when the a date range filter changes
$('.date-range-filter').change(function() {
$('#records').DataTable().draw();
});
});
Any help is appreciated.
I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)
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');
});
I have here HTML Code:
<div class="actResult" style="border: solid">
<table>
<tbody>
<tr>
<td>Order Number</td>
<td>1</td>
</tr>
<tr>
<td>Customer Number</td>
<td>3</td>
</tr>
<tr>
<td>Complaint Code</td>
<td>b</td>
</tr>
<tr>
<td>Receivable Receipt Number</td>
<td>5</td>
</tr>
<tr>
<td>Date Called</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Checkup</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Service</td>
<td>2014-03-21</td>
</tr>
<tr>
<td>Checkup Status</td>
<td>Y</td>
</tr>
<tr>
<td>Service Status</td>
<td>N</td>
</tr>
<tr>
<td>Technician Number Checkup</td>
<td>3</td>
</tr>
<tr>
<td>Technician Number Service</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
I want to get the values of the tags and put them into an array with the a structure like array("first td" => "second td"), so for this case the array would be array("Order Number" => "1", "Customer Number" => "3", "Complaint Code" => "b", ...) and so on.
After that, the final array would be sent into a PHP code.
I've been trying to extract some of the values from the HTML using var html = $(this).filter(function( index ){ return $("td", this) }).filter(":odd").text(); and various other combinations of filter(), but it doesn't seem to work for me.
How do I go about doing what I want to do?
jsFiddle Demo
You are going to want to use .each for that and iterate through the rows in the table. For each row, take the first cell (.eq(0)) as the key, and the second cell (.eq(1)) as the value. Place these in a result object.
//object to hold resulting data
var result = {};
//iterate through rows
$('.actResult tr').each(function(){
//get collection of cells
var $tds = $(this).find('td');
//set the key in result to the first cell, and the value to the second cell
result[$tds.eq(0).html()] = $tds.eq(1).text();
});
You can get the rows property of the table element and create an object based on the cells' value:
var rows = document.querySelector('.actResult table').rows,
data = {}, c, l = rows.length, i = 0;
for (; i < l; i++) {
c = rows[i].cells;
data[c[0].innerHTML] = c[1].innerHTML;
}
http://jsfiddle.net/tG8F6/