How to print array objects to a table? - javascript

I am a complete newbie in programming so be easy on me.
I want to print an array object into a table in HTML using getElementByID.
<script>
var ram = ["8GB", "3GB"];
var storage = ["500GB" , "120GB"];
document.getElementById("mac.r").innerHTML = ram[0];
document.getElementById("mac.s").innerHTML = storage[0];
</script>
And I want to print it in a table
<table width="600" border="6" cellpadding="5px">
<tr>
<td> Ram</td>
<td> Storage</td>
</tr>
<tr>
<td id="mac.r"></td>
<td id="mac.s"></td>
</tr>
</table>
I use a macbook and google chrome.

If you must keep your script inline place it at the bottom of your page. See below, you can view the fiddle here
Once the element exists that you need to populate, you then loop the the data you need and fill the related element with your data.
<html>
<body>
<table width="600" border="6" cellpadding="5px">
<tr>
<td> Ram</td>
<td> Storage</td>
</tr>
<tr>
<td id="mac.r"></td>
<td id="mac.s"></td>
</tr>
</table>
<script>
(function() {
var ram = ["8GB", "3GB"];
var storage = ["500GB", "120GB"];
var macR = document.getElementById('mac.r');
var macS = document.getElementById('mac.s');
for(var i = 0; i < ram.length; i++){
if (macR !== null) macR.innerHTML = macR.innerHTML + ram[i] + "<br>";
}
for(var i = 0; i < ram.length; i++){
if (macS !== null) macS.innerHTML = macS.innerHTML + storage[i] + "<br>";
}
})();
</script>
</body>
</html>

One simple approach is to use the array's build-in "forEach" method:
var ram = ["8GB", "3GB"],
storage = ["500GB" , "120GB"];
ram.forEach(function(element, index, array){
document.getElementById("mac.r").innerHTML += element;
});
storage.forEach(function(element, index, array){
document.getElementById("mac.s").innerHTML += element;
});
See it here: http://jsfiddle.net/S3CY4/
Be aware though its mostly supported in modern browsers and it may not be the most performant approach.

Related

tofixed(2) function apply to html class by name

The function is working correctly if simply var x (a digit)
but when I am trying to apply the same to html table class by name it is not working at all
<html>
<body>
<tr>
<td class="sal">45.515420</td>
</tr>
<script>
function myFunction() {
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = sal[i].innerHTML;
var newvalue = (sal.toFixed(2));
sal[i].innerHTML = newValue
}
}
onload = myFunction()
</script>
</body>
</html>
The provided code needs some changes, I'll try to address them:
Convert currentValue to number because toFixed is part of a Number
var currentValue = Number(sal[i].innerHTML);
onload = myFunction(), we can just call the function to run it on load
myFunction();
Wrapped <td class='sal'>45.515420</td> in a <table> to make the HTML valid
<table>
<tr>
<td class='sal'>45.515420</td>
</tr>
</table>
Applying those fixes gives:
function myFunction() {
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = Number(sal[i].innerHTML);
sal[i].innerHTML = currentValue.toFixed(2);
}
}
myFunction();
<table>
<tr>
<td class='sal'>45.515420</td>
</tr>
</table>
First, in order to use document.getElementsByClassName on td elements, you need to wrap your tr and td element inside table tag.
Second, toFixed() is a method for number and you need to convert the string to a number using Number() before you use toFixed().
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = sal[i].innerHTML;
var newValue = Number(currentValue).toFixed(2);
sal[i].innerHTML = newValue;
}
<html>
<body>
<table>
<tbody>
<tr>
<td class="sal">45.515420</td>
<td class="sal">49.515420</td>
</tr>
</tbody>
</table>
</body>
</html>
Along with all the other good advice, here's version that uses more modern JS practices.
querySelectorAll
forEach
Arrow function expressions
const sals = document.querySelectorAll('.sal');
sals.forEach(sal => {
const number = Number.parseFloat(sal.textContent);
sal.textContent = number.toFixed(2)
});
<table>
<tbody>
<tr>
<td class="sal">45.515420</td>
</tr>
</tbody>
</table>

How to show table rows based on URL parameter

Currently the page is accessed using a link, for instance help.html?show=charInPw.
The table is written in the following manner:
<table>
...
<tbody class="table-body">
<tr class="pwLen"><td colspan="5" class="subheading">Password Length</td></tr>
<tr class="pwLen"><td class="first">Minimum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="pwLen"><td class="first">Maximum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td colspan="5" class="subheading">Characters in Password</td></tr>
<tr class="charInPw"><td class="first">Minimum numeric characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td class="first">Minimum alphabetic characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
...
The CSS is as follows:
table tbody tr{
text-align: center;
display: none;
}
(There are also trs in thead and they are always shown by default.)
Then I have some Javascript code as follows (jQuery is not an option):
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
for (i = 0; i < document.getElementsByClassName(c); i++)
document.getElementsByClassName(c)[i].style.display='table-row';
</script>
However I am not able to get my rows to show.
How should I change the code on the page to show only the rows referenced by the show parameter?
Edit #1: As a test I did the following hard-coding but it didn't work too!
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
var trs = document.getElementsByClassName('pwLen');
for (i = 0; i < trs.length; i++)
trs[i].style.display='table-row';
</script>
Edit #2: I have combined two solutions below into one - please see https://jsfiddle.net/tea45p2o/. The demo output shown is what I want, however I am not able to see that when I save the file and open the page in my browser. What is going on?
With much help from BJohn and MrJ, I have come up with my solution as follows:
<script>
function show() {
var url = new URL(window.location.href);
var c = '.' + url.searchParams.get("show");
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
}
</script>
Then, I changed my <body> to
<body onLoad="show();">
Use below code:
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
You also need to append dot (.) with class name, which you are getting from the URL.
Please find the fiddle here
ŷou are missing to place .length
for (i = 0; i < document.getElementsByClassName(c).length; i++)
But I think it would be more readable on this way
for(let TR_x of [... document.getElementsByClassName(c) ]) {
TR_x.style.display='table-row';
}
but I definitely prefer
document.querySelectorAll('.'+c).forEach(trX=>{ trX.style.display='table-row' })

Reading text in columns from HTML tables

I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:
<table id="country_LE_table" style = "display:none">
<tr>
<td>Japan</td>
<td>83.7</td>
</tr>
<tr>
<td>Switzerland</td>
<td>83.4</td>
</tr>
</table>
My Javascript is:
<script type="text/javascript">
function getLifeExpectancy() {
var Country = "<?php echo $Country ?>";
document.write(Country); // this gets read OK
var table = document.getElementById("country_LE_table");
var tr = table.getElementsByTagName("tr");
document.write(tr.length); document.write("<br>"); // works as expected
for (var i = 0; i < tr.length; i++) {
document.write(tr[i].innerHTML); document.write("<br>"); // works well up to here
// the following doesn't work
var td = tr[i].getElementsByTagName("td")[0];
if (td = Country) { //need td.fullHTML/value/fullText?
return tr[i].getElementsByTagName("td")[1]; // return the number
}
document.getElementById("demo").innerHTML = getLifeExpectancy();
</script>
If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.
Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
{
}

Exporting HTML table to Excel using Javascript

I am exporting HTML table to xls foramt. After exporting if you open it in Libre Office, it works fine but the same opens a blank screen in Microsoft Office.
I don't want a jquery solution please provide any javascript solution.
Please help.
function fnExcelReport() {
var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange;
var j = 0;
tab = document.getElementById('table'); // id of table
for (j = 0; j < tab.rows.length; j++) {
tab_text = tab_text + tab.rows[j].innerHTML + "</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text = tab_text + "</table>";
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "Say Thanks to Sumit.xls");
} else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
On 2016-07-12, Microsoft pushed a security update for Microsoft Office. One of the effects of this update was to prevent HTML files from non-trusted domains from being opened by Excel, because they cannot be opened in Protected mode.
There is ALSO a registry setting that prevents Excel from opening files with the .XLS file extension whose contents do not match the official XLS file format, though it defaults to 'warn', not 'deny'.
Prior to this change, it was possible to save HTML data to a file with an XLS extension, and Excel would open it correctly - possibly giving a warning first that the file did not match the Excel format, depending on the user's value for the ExtensionHardening registry key (or related config values).
Microsoft has made a knowledge-base entry about the new behavior with some suggested workarounds.
Several web applications that previously relied on exporting HTML files as XLS have run into trouble as a result of the update - SalesForce is one example.
Answers from before July 12th 2016 to this and similar questions are likely to now be invalid.
It's worth noting that files produced ON THE BROWSER from remote data do not fall afoul of this protection; it only impedes files downloaded from a remote source that is not trusted. Therefore one possible approach is to generate the .XLS-labelled HTML file locally on the client.
Another, of course, is to produce a valid XLS file, which Excel will then open in Protected mode.
UPDATE: Microsoft has released a patch to correct this behavior: https://support.microsoft.com/en-us/kb/3181507
SheetJS seems perfect for this.
To export your table as an excel file use the code in this link(along with SheetJS)
Just plug in your table element's id into export_table_to_excel
See Demo
If CSV format is good for you, here is an example.
Ok...I just read a comment where you explicitly say it isn't good for you. My bad for not learning to read before coding.
As far I know, Excel can handle CSV.
function fnExcelReport() {
var i, j;
var csv = "";
var table = document.getElementById("table");
var table_headings = table.children[0].children[0].children;
var table_body_rows = table.children[1].children;
var heading;
var headingsArray = [];
for(i = 0; i < table_headings.length; i++) {
heading = table_headings[i];
headingsArray.push('"' + heading.innerHTML + '"');
}
csv += headingsArray.join(',') + ";\n";
var row;
var columns;
var column;
var columnsArray;
for(i = 0; i < table_body_rows.length; i++) {
row = table_body_rows[i];
columns = row.children;
columnsArray = [];
for(j = 0; j < columns.length; j++) {
var column = columns[j];
columnsArray.push('"' + column.innerHTML + '"');
}
csv += columnsArray.join(',') + ";\n";
}
download("export.csv",csv);
}
//From: http://stackoverflow.com/a/18197511/2265487
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();">EXPORT
</button>
<table id="table">
<thead>
<tr>
<th>Head1</th>
<th>Head2</th>
<th>Head3</th>
<th>Head4</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
</tr>
<tr>
<td>31</td>
<td>32</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>41</td>
<td>42</td>
<td>43</td>
<td>44</td>
</tr>
</tbody>
</table>
add this to your head:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
and add this as your javascript:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
Jfiddle: http://jsfiddle.net/cmewv/537/
try this
<table id="exportable">
<thead>
<tr>
//headers
</tr>
</thead>
<tbody>
//rows
</tbody>
</table>
Script for this
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
You can use tableToExcel.js to export table in excel file.
This works in a following way :
1). Include this CDN in your project/file
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel#v1.0.4/dist/tableToExcel.js"></script>
2). Either Using JavaScript:
<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>
function exportReportToExcel() {
let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xls`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
}
3). Or by Using Jquery
<button id="btnExport">EXPORT REPORT</button>
$(document).ready(function(){
$("#btnExport").click(function() {
let table = document.getElementsByTagName("table");
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xls`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
});
});
You may refer to this github link for any other information
https://github.com/linways/table-to-excel/tree/master
or for referring the live example visit the following link
https://codepen.io/rohithb/pen/YdjVbb
This will download the export.xls file
Hope this will help someone :-)
<hrml>
<head>
<script language="javascript">
function exportF() {
//Format your table with form data
document.getElementById("input").innerHTML = document.getElementById("text").value;
document.getElementById("input1").innerHTML = document.getElementById("text1").value;
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.C:\\Users\WB-02\desktop\Book1.xlsx,' + escape(html); // Set your html table into url
var link = document.getElementById("downloadLink");
link.setAttribute("href", url);
link.setAttribute("download", "export.xls"); // Choose the file name
link.click(); // Download your excel file
return false;
}
</script>
</head>
<body>
<form onsubmit="return exportF()">
<input id="text" type="text" />
<input id="text1" type="text" />
<input type="submit" />
</form>
<table id="table" style="display: none">
<tr>
<td id="input">
<td id="input1">
</td>
</tr>
</table>
<a style="display: none" id="downloadLink"></a>
</body>
</html>
İf you have a too much column , try to use this code. You can split easily.
function iterate( tab, startIndex , rowCount){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
J=startIndex;
for(j = startIndex ; j < rowCount ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
}
function fnExcelReport()
{
var indirilecekSayi = 250;
var toplamSatirSayisi = 0;
var baslangicSAyisi = 0;
var sonsatirsayisi = 0;
tab = document.getElementById('myTable'); // id of table
var maxRowCount = tab.rows.length;
toplamSatirSayisi = maxRowCount;
sonsatirsayisi=indirilecekSayi;
var kalan = toplamSatirSayisi % indirilecekSayi;
var KalansızToplamSatir=ToplamSatirSayisi-kalan;
var kacKati=Tsh / indirilecekSayi;
alert(maxRowCount);
alert(kacKati);
for (let index = 0; index <= kacKati; index++) {
if (index==kacKati) {
baslangicSAyisi =sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+kalan;
iterate(tab, baslangicSAyisi, sonsatirsayisi);
}else{
iterate(tab , baslangicSAyisi , sonsatirsayisi);
baslangicSAyisi=sonsatirsayisi;
sonsatirsayisi=sonsatirsayisi+indirilecekSayi;
if(sonsatirsayisi>ToplamSatirSayisi){
sonsatirsayisi=baslangicSAyisi;
}
}
}
}

Removing a TableCellElement from an Array stops innerHTML from working?

Using JavaScript in Greasemonkey, I'm attempting to pull individual cells and read the innerHTML of each cell to search for a given string.
There's a table of 3x3, and I want to search them in the order of the center first, then depending on situation, move to not-necessarily linear progression (i.e. top-left, top, left, top-right, bottom-left, right, bottom, bottom-right).
I've put each of the cells into an array, and using splice(), I assign the cell to a variable. For testing purposes, I throw up 2 alerts with the cell variable itself, then the cell innerHTML.
When I just use the variable, the alert says [object HTMLTableCellElement], but the innerHTML is undefined.
I've created a mock page to show my example. here's the code (Also at jsBin).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4<br>
center
</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</table>
<script language="JavaScript">
var tables = document.getElementsByTagName("table");
tables[0].style.border = "thin solid red";
tables[0].id = "grid";
var grid = tables[0];
var cells = new Array();
cells[0] = grid.rows[0].cells[0]; // nw
cells[1] = grid.rows[0].cells[1]; // n
cells[2] = grid.rows[0].cells[2]; // ne
cells[3] = grid.rows[1].cells[0]; // w
cells[4] = grid.rows[1].cells[1]; // c
cells[5] = grid.rows[1].cells[2]; // e
cells[6] = grid.rows[2].cells[0]; // sw
cells[7] = grid.rows[2].cells[1]; // s
cells[8] = grid.rows[2].cells[2]; // se
var grid_string = "";
function HumanCount(cell) {
var human_regex = /Human/;
var humans = cell.innerHTML.split(human_regex);
var humans_length = humans.length - 1;
return humans_length;
}
for (a = 0; a < 9; a++) {
cells[a].count = HumanCount(cells[a]);
grid_string += cells[a].count + " ";
if (a == 2 || a == 5) {
grid_string += "<br>";
}
}
var direction = 0; // nw
var center = cells.splice(4, 1);
alert("center: " + center);
alert("innerHTML: " + center.innerHTML);
</script>
</body>
</html>
center is not an element, so it has no innerHTML property.
center is an array of elements, so if you use:
alert ("innerHTML: " + center[0].innerHTML);
you'll see what you expect.
~~~
That alert alert("center: "+center); is misleading, as it shows <td> the same as [<td>].
For more accurate (and less annoying) debugging don't use alert(). Use console.log, EG: console.log ("center: ", center); -- which would show the array as different from the element and doesn't throw up a modal dialog.

Categories