Reputation: 558
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>[email protected]</td>
<td>9876543210</td>
<td>email</td>
</tr>
<tr>
<td>John</td>
<td>Paul</td>
<td>[email protected]</td>
<td>9638527410</td>
<td>phone</td>
</tr>
<tr>
<td>Math</td>
<td>willams</td>
<td>[email protected]</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,[email protected],9876543210,email),
(John,Paul,[email protected],9638527410,phone),
(Math,willams,[email protected],99873210456,phone)
Upvotes: 8
Views: 15599
Reputation: 48427
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.
Upvotes: 3
Reputation: 292
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');
Upvotes: 8