Convert HTML table to array [duplicate] - javascript

This question already has answers here:
Convert html table to array in javascript
(5 answers)
Closed 7 years ago.
I have a html table
<table>
<tr>
<th>Type</th>
<th>Text</th>
<th>Time</th>
<th>Notification Time</th>
</tr>
<tr>
<td>Lab1</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Monday, Wednessday</td>
</tr>
<tr>
<td>Lab2</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Tuesday, Wednessday</td>
</tr>
</table>
Now I want to use those values of <td> and form an array in php or jquery.
Any idea how to do it in the most simplest way?

In jquery:
var tdCollection = $("table").find("td");
var array = [];
$.each(tdCollection, function(key, el){
array.push($(el).text());
});
console.log(array);
fiddle: http://jsfiddle.net/qqdwct7h/
But it would be better to set an id attribute for the table, beacuse using $(table) isn`t best way to select a certain table.

Check this jQuery traversing and Ajax sample :)
<script type="text/javascript">
var tableRows = $("table tr"),
currentRow,
tableData = [];
for (var i = tableRows.length; i--;) {
currentRow = $(tableRows[i]);
tableData.push({
field1: $(":nth-child(1)", currentRow),
field2: $(":nth-child(2)", currentRow),
field3: $(":nth-child(3)", currentRow),
field4: $(":nth-child(4)", currentRow)
});
}
//Sample Test to verify if data is fetched
console.log(tableData);
$.ajax({
url: "sample-ajax-handler.php",
type: "POST",
data: tableData,
success: function (e) {
//do what you want here :)
}
});
</script>

I wrote a fiddle that allows to generate an array based on the column:
http://jsfiddle.net/5vfm6k6q/2/
Works like this:
var parser = new ArrayParser(),
result = parser.getArray('#table', 'Type'); // table selector, column

Related

Sending null values to php from post js

I'm trying to send values obtained from datable to a php file but sends null
and return empty values from php
This is what'ive tried
document.addEventListener("DOMContentLoaded", function(event) {
const allButtons = document.querySelectorAll('#tablaUnidades td button');
allButtons.forEach(function(elem) {
elem.addEventListener("click", (e)=> {
e.preventDefault();
var allCells = elem.parentNode.parentNode.cells;
codigo = allCells[0].textContent;
deslar = allCells[1].textContent;
descor = allCells[2].textContent;
opcion = allCells[3].textContent;
console.log(codigo,deslar,descor,opcion);
fetch('bd/crud_unidades.php',{
method: "POST",
data: {codigo, deslar, descor, opcion}
})
.then(res=>res.text())
.then(data=>{
console.log(data);
})
});
});
});
<table class="table table-bordered" id="tablaUnidades" width="100%" cellspacing="0" method="post">
<thead>
<tr>
<th>CODIGO</th>
<th>DESCRIPCIÓN LARGA</th>
<th>DESCRIPCIÓN CORTA</th>
<th>ACCIÓN</th>
</tr>
</thead>
<tbody>
<tr>
<td id="codigo"> value 1</td>
<td id="deslar"> value 2</td>
<td id="descor">value 3</td>
<td><button class='btn btn-primary btnVER' id="VER" name="VER"> Click Me</button></a></td>
</tr>
<?php
}
?>
</tbody>
</table>
crud_unidades.php :
<?php
$codigo = var_dump($_POST['codigo']);
$deslar = var_dump($_POST['deslar']);
$descor = var_dump($_POST['descor']);
$opcion = var_dump($_POST['opcion']);
echo var_dump($codigo);
?>
Now I have no idea on how to assign that javascript variable to the php one to use the phpvariable to look up stuff in my database
please help
The source of your woes is the way you're forming your POST object. You're not assigning key/value pairs, you're just creating an object with values - which is not a valid object and I'll best javascript is throwing an error on that.
Your fetch should look more like this:
fetch('bd/crud_unidades.php',{
method: "POST",
data: {codigo: codigo, deslar: deslar, descor: descor, opcion: opcion}
})
Along those lines, if you update your table cell html in the future, this line might stop working:
var allCells = elem.parentNode.parentNode.cells;
Rather, try using closest(selector) which will work it's way up the DOM tree until it finds the selector match, like:
var allCells = elem.closest('tr').querySelectorAll('td');
var formData = new FormData;
var arr = {'codigo': codigo, 'deslar': deslar, 'descor': descor, 'opcion': opcion};
Object.entries(arr).forEach(([key, value]) => {
formData.append(key,value);
});
fetch('bd/crud_unidades.php',{
method: "POST",
cors: "CROS",
body: formData,
})
This was the correct way

Parsing html with cheerio

I used cheerio for the first time today
This is a simplified version of the html source I want.
<div id="country-table">
<!-- div duplicate cause style -->
<div>
<div>
<table>
<tbody>
<tr>
<td>1</td>
<td>USA</td>
<td>1.6</td>
<td>75.8</td>
<td>132,000</td>
</tr>
<tr>
<td>2</td>
<td>INDIA</td>
<td>12123</td>
<td>1322</td>
<td>123213</td>
</tr>
<tr>
<td>3</td>
<td>BRAZIL</td>
<td>3123</td>
<td>213123</td>
<td>134</td>
</tr>
<tr>
<!-- and more... -->
</tbody>
</table>
</div>
</div>
</div>
and i tried to this:
const axios = require("axios").default;
const cheerio = require("cheerio").default;
axios.get("https://coronaboard.kr").then((html) => {
const arr = [];
const $ = cheerio.load(html.data, { xml: true, xmlMode: true });
const data = $("#country-table>div>div>table>tbody").each((index, item) => {
arr.push(item);
});
console.log(arr);
});
I want to put information in td into tr.
ex){number:x,name:USA,confirmed:x,and more...}
If anyone knows how to do it, please answer me!
If you're wanting to extract the data from the table, then this will help. Follow the comments to help you understand how it works.
var $ = cheerio.load(html.data);
// targets the specific table with a selector
var html_table = $('#country-table>div>div>table');
// gets table cell values; loops through all tr rows
var table_data = html_table.find('tr').map(function() {
// gets the cells value for the row; loops through each cell and returns an array of values
var cells = $(this).find('td').map(function() {return $(this).text().trim();}).toArray();
// returns an array of the cell data collected
return [cells];
}).toArray();
// output table data
console.log('table_data', table_data);

Iterate through selected rows in Datatables

I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.

Convert table HTML to JSON

I have this:
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
And I need a JSON format.
{"Name":"Carlos","Age": 22}
I've tried with https://github.com/lightswitch05/table-to-json but it doesn't work for the headings in every row :(
EDIT: http://jsfiddle.net/Crw2C/773/
You can convert the table in the OP to the required format by first converting it to an Object, then using JSON.stringify to get the required string:
<table id="t0">
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<script>
function tableToJSON(table) {
var obj = {};
var row, rows = table.rows;
for (var i=0, iLen=rows.length; i<iLen; i++) {
row = rows[i];
obj[row.cells[0].textContent] = row.cells[1].textContent
}
return JSON.stringify(obj);
}
console.log(tableToJSON(document.getElementById('t0'))); // {"Name:":"Carlos","Age:":"22"}"
</script>
However, that is an ad hoc solution, so will need some work to be adapted to a more general case. It shows the concept though.
Note that there is no guarantee that the object properties will be returned in the same order as they appear in the table, you may get {"Age:":"22","Name:":"Carlos"}.
Assuming all you need is to get the first/second cells of each row as key/value pairs, you can use .reduce() to iterate of the rows and just grab the text content of .cells[0] and .cells[1] to use as each key/value pair:
var t = document.querySelector("table");
var j = [].reduce.call(t.rows, function(res, row) {
res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
return res
}, {});
document.querySelector("pre").textContent = JSON.stringify(j, null, 2);
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<pre></pre>
The Array.prototype.reduce method takes a collection and uses an accumulator to reduce it down to whatever state you want. Here we just reduce it to an object, so we pass one in after the callback.
For every row, we use the first cell's content as the object key, and the second cell's content as the value. We then return the object from the callback so that it's given back to us in the next iteration.
Finally, .reduce() returns the last thing we returned (which of course is the object we started with), and that's your result.
var t = document.querySelector("table");
var j = [].reduce.call(t.rows, function(res, row) {
res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
return res
}, {});
document.querySelector("pre").textContent = JSON.stringify(j);
<table>
<tr>
<th>Name:</th>
<td>Carlos</td>
</tr>
<tr>
<th>Age:</th>
<td>22</td>
</tr>
</table>
<pre></pre>
The Table-to-JSON library that you are using is expecting a different format in your table.
It is expecting a table with all of your headers in the first row, followed by the data in subsequent rows.
In other words, it's expecting your table to be structured like this
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Carlos</td>
<td>22</td>
</tr>
</table>
Here's a forked version of your JSFiddle in which this is working.

JSON Object into Mustache.js Table

I'm trying to create a table with a JSON Object using Mustache.js.
I wanted it to show two rows, however it's only showing the second row only.
I suspect that the first row is being overwritten by the second when it's being bound again in the loop.
How do I work my way around it? Or is there a better structure I should follow?
Javascript:
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
Template :
<script id="user-template" type="text/template">
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</script>
table:
<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable">
</tr>
</table>
In additon to your own solution, you should consider using mustache to repeat the row for you:
<script id="user-template" type="text/template">
{{#people}}
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = {people: JSON.parse(text)};
$(document).ready(function() {
var template = $('#user-template').html();
var info = Mustache.render(template, obj);
$('#ModuleUserTable').html(info);
});
I figured out that instead of
$('#ModuleUserTable').html(info);
it should be :
$('#ModuleUserTable').append(info);
Template should be :
<script id="user-template" type="text/template">
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
</script>
and ID should not be on the table row tag. Instead it should be on the table itself:
<table border="1" id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
The moment when it appends, it adds a new row into the table with the JSON data.

Categories

Resources