This is my Html Table.
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Id</th>
<th>Phone Number</th>
<th>Prefered Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>Miles</td>
<td>james#abcd.com</td>
<td>9876543210</td>
<td>email</td>
</tr>
<tr>
<td>John</td>
<td>Paul</td>
<td>john#abcd.com</td>
<td>9638527410</td>
<td>phone</td>
</tr>
<tr>
<td>Math</td>
<td>willams</td>
<td>Math#abcd.com</td>
<td>99873210456</td>
<td>phone</td>
</tr>
</tbody>
</table>
In this table there is Save Button.
<input type="button" id="txt" value="Save" />
Button Code
function tableToJson(table) {
var data=[];
var headers=[];
for (var i=0;
i < table.rows[0].cells.length;
i++) {
headers[i]=table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
for (var i=1;
i < table.rows.length;
i++) {
var tableRow=table.rows[i];
var rowData= {}
;
for (var j=0;
j < tableRow.cells.length;
j++) {
rowData[headers[j]]=tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
When the click the save button, The html table data will stored in the .txt document without <table>,<tr>,<td>. The data storing format will be like below format.
(James,Miles,james#abcd.com,9876543210,email),
(John,Paul,john#abcd.com,9638527410,phone),
(Math,willams,Math#abcd.com,99873210456,phone)
Slightly clearer code than the above answer that works for any number of columns
var retContent = [];
var retString = '';
$('tbody tr').each(function (idx, elem)
{
var elemText = [];
$(elem).children('td').each(function (childIdx, childElem)
{
elemText.push($(childElem).text());
});
retContent.push(`(${elemText.join(',')})`);
});
retString = retContent.join(',\r\n');
jsfiddle with the full code
First of all, you have to create data which contains all user details.
userDetails='';
$('table tbody tr').each(function(){
var detail='(';
$(this).find('td').each(function(){
detail+=$(this).html()+',';
});
detail=detail.substring(0,detail.length-1);
detail+=')';
userDetails+=detail+"\r\n";
});
Then you need to save file:
var a=document.getElementById('save');
a.onclick=function(){
var a = document.getElementById("save");
var file = new Blob([userDetails], {type: 'text/plain'});
a.href = URL.createObjectURL(file);
a.download = "data.txt";
}
Here is a working solution: jsfiddle.
Related
I found a code example online, about how to convert HTML table into CSV. The code seems fine.
https://jsfiddle.net/3p0r2haq/12/
function download_csv(csv, filename) {
var csvFile;
var downloadLink;
// CSV FILE
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th ");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
document.querySelector("button").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
However, the document has node <br>, which will mass up str. I added an example here. My question is how to avoid the <br> node or remove them all before query?
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Geronimo</td>
<td>26</td>
<td><br>France</td>
</tr>
<tr>
<td>Natalia</td>
<td>19</td>
<td>Spain</td>
</tr>
<tr>
<td>Silvia</td>
<td>32</td>
<td>Russia</td>
</tr>
</tbody>
</table>
So the result will mass up like the image
Just change
row.push(cols[j].innerText);
To
row.push(cols[j].innerText.trim());
Using trim() will remove the \n and any other whitespace in a cell
function export_table_to_csv(html, filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th ");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText.trim());
csv.push(row.join(","));
}
// Download CSV
// download_csv(csv.join("\n"), filename);
// log results for demo instead of download
console.log(csv)
}
export_table_to_csv()
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Geronimo</td>
<td>26</td>
<td><br>France</td>
</tr>
<tr>
<td>Natalia</td>
<td>19</td>
<td>Spain</td>
</tr>
<tr>
<td>Silvia</td>
<td>32</td>
<td>Russia</td>
</tr>
</tbody>
</table>
I am using pound symbol(£) in table head(th) and i am exporting the table in CSV format using javascript. But the CSV file is showing the pound(£) symbol like "£".
I tried various solutions provided in SO threads. But none of them worked for me.
How can I fix this issue?
Below is the code of the table:
<thead>
<tr>
<th>Property Name</th >
<th>Description</th >
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead
I am using the below JavaScript function to export the table into CSV.
function exportTableToCSV(filename,userName) {
var csv = [];
var rows = document.querySelectorAll("table#"+userName+" tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
The output is like the one in the below screenshot.
Can you replace js and check.
function exportTableToCSV(filename, userName) {
var csv = [];
var rows = document.querySelectorAll("table#" + userName + " tr");
for (var i = 0; i < rows.length; i++) {
var row = [],
cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
var csvString = csv;
var universalBOM = "\uFEFF";
var a = window.document.createElement('a');
a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(universalBOM + csvString));
a.setAttribute('download', filename);
window.document.body.appendChild(a);
a.click();
}
exportTableToCSV('test.csv', 'velu');
<table id="velu">
<thead>
<tr>
<th>Property Name</th>
<th>Description</th>
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead>
</table>
I need to move the row/s that is matched with the inputted string.
on the code below you need to click first the row before you can move that particular row to the top.
Instead of clicking the row, I just wanted to input a string or char then onclick, if there's a match on the html table, the row that matched or like on the string inputted will be moved on the top of the table grid.
var index;
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if (direction === "up") {
if (index < rows.length) {
parent.insertBefore(rows[index], rows[index - index + 1]);
index--;
}
}
}
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
</table>
<input type="text" id="txt">
<button onclick="upNdown('up');">↑</button>
what I need to do is upon click of the button, find the matching data and move the row to the top.
If I correctly understand you problem, Think this is your answer. This code find the first match of input and move that to first row. If the input be empty, it will do nothing.
var index = 0;
function findMatchRow(rows, str) {
if (!str.length) {
return null;
}
for (var i = 1; i < rows.length; i++) {
for (var j = 0; j < rows[i].children.length; j++) {
if (rows[i].children[j].textContent.match(str)) {
return i;
}
}
}
return 0;
}
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index && index > -1 ? index : 0].parentNode,
inpt = document.getElementById("txt").value;
var matchedRow = findMatchRow(rows, inpt);
if (matchedRow) {
if (direction === "up") {
index = matchedRow;
parent.insertBefore(rows[index], rows[index - index + 1]);
index--;
if (index < 0) {
index = rows.length - 1;
}
}
}
}
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
</tr>
</table>
<input type="text" id="txt">
<button onclick="upNdown('up');">↑</button>
I have a two webpages. eventsCreated and createAnEvent. In createAnEvent, a form is used to allow users' inputs. The inputs are then stored to local storage with the following function:
document.addEventListener("DOMContentLoaded",docIsReady);
var createEvent;
function docIsReady(){
createEvent=localStorage.getItem("createEvent");
if (createEvent==null){
CreateEvent=[];
}
else {
createEvent=JSON.parse(createEvent);
}
}
function saveToStorage() {
var one;
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
localStorage["X"]=JSON.stringify(positions);
var r=localStorage["X"];
r=JSON.parse(r);
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
one={"name":nameofevent,"pos":r,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
createEvent.push(one);
localStorage.setItem("createEvent",JSON.stringify(createEvent));
//alert(JSON.stringifys(one));
//alert(one.pos[0]); //to get one position
return false;
}
I made createEvent an array so as to store the multiple inputs because there cannot be only one event created. In the eventsCreated page, I need to display the user inputs in a table that looks something like this :
<table border="1px" id="list">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</table>
I am not sure how to use javascript to get the event details that the user has entered in the createAnEvent page and display it in the table.
This is the javascript:
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i=0; i<one.length; i++) {
var row = table.insertRow(i);
for (var j=0; j<=6; j++) {
var cell = row.insertCell(j);
}
cell[0].innerHTML = "one[0]";
cell[1].innerHTML = "one[1]";
cell[2].innerHTML = "one[1]";
cell[3].innerHTML = "one[3]";
cell[4].innerHTML = "one[4]";
cell[5].innerHTML = "one[5]";
cell[6].innerHTML = "one[6]";
}
}
I would use jquery to add elements to your page.
But you can use the dom if you like.
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i = 0; i < one.length; i++) {
var this_tr = document.createElement("tr");
for (var j=0; j < one[i].length; j++) {
var this_td = document.createElement("td");
var text = document.createTextNode(one[i][j]);
this_td.appendChild(text);
this_tr.appendChild(this_td);
}
table.appendChild(this_tr);
}
This should work for you or close to it. You table is also wrong please correct it to this.
<table border="1px">
<thead>
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</thead>
<tbody id="list">
</tbody>
</table>
See for examples:
http://www.w3schools.com/jsref/met_node_appendchild.asp
I want to create static/dynamic table. All cell <th> and the first two columns <td> of row are static. Content others cells I want to create dynamically using jQuery script.
I do not know how I start. Data to cell I have saved at JSON format (array) as:
{
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
}
HTML:
<table id="personDataTable" style="border: 1px #e3ffg3 solid; text-align: center;">
<tr class="bg02">
<th colspan="2">Name</th>
<th width="100px">Sensor 1</th>
<th width="100px">Sensor 2</th>
<th width="100px">Sensor 3</th>
<th width="100px">Sensor 4</th>
</tr>
<tr id="row1">
<td class="bg02">A</td>
<td class="bg02">Out64H</td>
<td>element[index]</td>
<td>element[index+1]</td>
<td>element[index+2]</td>
<td>element[index+3]</td>
</tr>
<tr id="row2">
<td class="bg02">R</td>
<td class="bg02">In128Birh</td>
<td>element[index]</td>
<td>element[index+1]</td>
<td>element[index+2]</td>
<td>element[index+3]</td>
</tr>
</table>
Static text in the every <tr> is necassary because text is not in json file.
Can ask for help with create javascript script?
Thanks very much
See this jsfiddle: http://jsfiddle.net/9zr6z70g/3/
The jQuery code is this way:
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
for (var index=0; index<4; index++) {
$(row1cells[index+2]).html(data1[index]);
$(row2cells[index+2]).html(data2[index]);
}
});
For multiple EX data, do it this way:
var exCount = 2;
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
$(document).ready(function(){
for (var index=1; index<=exCount; index++) {
var cells = $("#row"+index+" td");
var values = data["EX"+index][0];
for (var jndex=0; jndex<4; jndex++) {
$(cells[jndex+2]).html(values[jndex]);
$(cells[jndex+2]).html(values[jndex]);
}
}
});
More details for multiple EX, see jsfiddle: http://jsfiddle.net/9zr6z70g/7/
This code is suitable for me, but variable EX are more than one hundred.
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
for (var index=0; index<4; index++) {
$(row1cells[index+2]).html(data1[index]);
$(row2cells[index+2]).html(data2[index]);
}
});
I tried modify the code using for loop following. This solution do not work correctly.
var data = {
"EX1":[["1","8","16","24"]],
"EX2":[["0","100200","109f","ffffffff"]]
};
var data1 = data.EX1[0];
var data2 = data.EX2[0];
$(document).ready(function(){
for (j=1; j<4; j++) {
var pom = "row"+[j]+"cells";
var pom2 = "#row"+[j]+" td";
var pom3 = "$"+'("'+pom2+'")';
for (var index=0; index<4; index++) {
$(pom3+[index+2]).html(data[j][index]);
}
}
});
Can ask for help with modify? Thanks