Export HTML table from an iframe to CSV - javascript

I'm trying to look for a script (with no progess) that could export an HTML table that I am able to get from an iframe. The table is inside the iframe and I can get and display its contents on my parent document.
<script type="text/javascript">
function myFunction() {
var myIFrame = document.getElementById("myIframe");
var content = myIFrame.contentWindow.document.getElementById("table").innerHTML;
alert(content);
// suggestions here to export the table to CSV
}
</script>
I am not asking you to write the code for me. I would appreciate if someone could point me to the right direction.

I made a simple jsfiddle to illustrate the idea. https://jsfiddle.net/anjvsqt7/9/
The code snippet from the example I made is below:
var csvStr = '';
var table = $('#table');
var rows = table.children('tbody').children('tr');
var len = rows.length;
for(var i=0;i<len;i++) {
var row = $(rows[i]);
var cols = row.children('td');
for(var j=0;j<cols.length;j++) {
col = cols[j];
csvStr += col.innerText + ',';
}
csvStr += '\n';
}
//console.log(csvStr);

I have used datatables to do this in the past.
It gives you options to display buttons that can be used to export to CSV, Excel and PDF as well as exporting to your clipboard.
Example page

Related

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

how can i make this ajax code work with any kind of html file

I have a ajax call which will get some data from database and I have to load these into a html file. But, the problem is I have different html files and I do not know the content of html file
I have tried it for around 2-3 days and have searched different ways to append data to a html file.
I have made some changes in the code. please assume that the code is working fine.
thank you.
$.ajax({
type: "GET",
url: "api/dataFromDataBase",
success: function (data) {
tableHead = data[0].split("?");//contains data from database
$("#databaseContent").append("<tr>");
for (var i = 0; i < 80; i++) {
$("#databaseContent").append("<th>" + tableHead[i] + "</th>");
}
$("#tableHeading").append("</tr>");
tableHead += data[0];
$("#FromHtml").append(data[1]);
},
});
in this file #databaseContent is an id in the html, so i can easily append the data. but I have no idea about what the html contains. Is their any way i can append data to it??
If you don't have a point of injection on a successful Ajax call. You can append this entire table at the end of the html page.
// all of this within the success call of the AJAX
var tableHead = data[0].split("?");//contains data from database
var tableEle = document.createElement("table");
var tableBody = document.createElement("tbody");
var tableTr = document.createElement("tr");
for (var i = 0; i < 80; i++) {
var cell = document.createElement("th");
var cellText = document.createTextNode(tableHead[i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
tableBody.appendChild(tableTr);
tableEle.appendChild(tableBody);
document.body.appendChild(tableEle);
What we are trying to do here is, create a table element and within the loop creating the content of the table and at the end we're appending the newly created table to the
"document.body". This should work for all html since all html pages have a body tag.

Get value from a JSON file with multi dimensional array using jQuery $.getJSON method

I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo

innerHTML not updating display

First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}

Export html table to excel using javascript

I tried to export my html table to excel using the code given in this Gist. But after exporting, when i opened the file, It displays the html code of the demo page in excel. Can anyone please give the correct sample of javascript used to export the html table to excel (Should be opened in office Calc too).
EDIT: Attached the image screenshot.
Here is a function I made.
Add "remove" class on elements you do not want to show in the excel.
function exportExcel(id,name){ //<table> id and filename
var today = new Date();
var date = ('0'+today.getDate()).slice(-2)+"-"+('0'+(today.getMonth()+1)).slice(-2)+"-"+today.getFullYear();
var file_name = name+"_"+date+".xls"; //filename with current date, change if needed
var meta = '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
var html = $("#"+id).clone();
html.find('.remove').remove(); //add the 'remove' class on elements you do not want to show in the excel
html.find('a').each(function() { //remove links, leave text only
var txt = $(this).text();
$(this).after(txt).remove();
});
html.find('input, textarea').each(function() { //replace inputs for their respectives texts
var txt = $(this).val().replace(/\r\n|\r|\n/g,"<br>");
$(this).after(txt).remove();
});
html.find('select').each(function() { //replace selects for their selected option text
var txt = $(this).find('option:selected').text();
$(this).after(txt).remove();
});
html.find('br').attr('style', "mso-data-placement:same-cell"); //make line breaks show in single cell
html = "<table>"+html.html()+"</table>";
var uri = 'data:application/vnd.ms-excel,'+encodeURIComponent(meta+html);
var a = $("<a>", {href: uri, download: file_name});
$(a)[0].click();
}
Call it on an event, example:
$("#export_button").click(function(e){
exportExcel("table_id", "filename");
});

Categories