display contents of csv file in html page - javascript

I have a standalone HTML page (no webserver) and I'm after some javascript code that will display the contents of a .csv file in the page.
The .csv file contains a list of usernames that I would like to be displayed. I'm doing it this way as the people that need to update the list know nothing of HTML and initially thought this would be an easier way to do it.
All the code snippets that I have found either try to upload a file and then only display the contents till you reload the page again or I don't have enough knowledge to tweak the code to work.
Any help appreciated & TYIA
Andy
#Barthy code that is very close to what I would like is this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
but would like to get data from CSV file
#cars10 example of what is in the csv file:
Heading_1,Heading_2,Heading_3,Heading_4
John, Smith, 29, Male
Andy, Jones, 32, Male
Abbey, Stewart, 35, Female
if that helps
Solution so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
<script>
window.onload=function(){ with (new XMLHttpRequest()) {
onreadystatechange=cb; open('GET','data.csv',true); responseType='text';send();
}}
function cb(){if(this.readyState===4)document.getElementById('main')
.innerHTML=tbl(this.responseText); }
function tbl(csv){ // do whatever is necessary to create your table here ...
return csv.split('\n')
.map(function(tr,i){return '<tr><td>'
+tr.replace(/\t/g,'</td><td>')
+'</td></tr>';})
.join('\n'); }
</script>
</head>
<body>
<h2>Hey, this is my fabulous "dynamic" html page!</h2>
<table id="main"></table>
</body>
</html>

Here is a complete working example (works even on a local directory, i.e. no web server at all!). This is a plain JavaScript solution. Personally, I would always use jquery, but in this simple case you can do without it.
The page expects the csv-file ("csv.txt") in the same directory. But it is up to you to specify another (relative) path in the oReq.open() line.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function(){ with (new XMLHttpRequest()) {
onreadystatechange=cb; open('GET','csv.txt',true); responseType='text';send();
}}
function cb(){if(this.readyState===4)document.getElementById('main')
.innerHTML=tbl(this.responseText); }
function tbl(csv){ // do whatever is necessary to create your table here ...
return csv.split('\n')
.map(function(tr,i){return '<tr><td>'
+tr.replace(/\t/g,'</td><td>')
+'</td></tr>';})
.join('\n'); }
</script>
</head>
<body>
<h2>Hey, this is my fabulous "dynamic" html page!</h2>
<table id="main"></table>
</body>
</html>
I got my inspiration from here: Javascript - read local text file .

Related

I was not able to see images while converting html page to pdf using javascript

here is my code while i download pdf images attributes of html are missing.
suppose in cases like generating invoices we should print tables containing details along with logo.
but images are not displaying in downloaded pdf using this code.Provide me with possible resolution and reason for this.thanks in advance
$(document).on('click', '#btn', function() {
let pdf = new jsPDF();
let section = $('body');
let page = function() {
pdf.save('pagename.pdf');
};
pdf.addHTML(section, page);
})
html,
body {
overflow-x: hidden;
}
#btn {
padding: 10px;
border: 0px;
margin: 50px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML with Image</title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<style type="text/css">
</style>
</head>
<body>
<button id="btn">Convert to PDF</button>
<div id="text">
<h2>HTML Page with Image to PDF</h2>
<img src="http://photojournal.jpl.nasa.gov/jpeg/PIA17555.jpg" width="300px">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script src="custom.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
all the html elements are working fine except images . kindly help me with resolving this.
jsPdf does not support adding images the way you are trying to add them, because addtHtml function uses the html2canvas module, to convert your Html to canvas, so jsPdf can render it into pdf. Please check this link below.
https://weihui-guo.medium.com/save-html-page-and-online-images-as-a-pdf-attachment-with-one-click-from-client-side-21d65656e764

JavaScript function not called at onclick button in Visual Studio 2015 Community Edition

I am learning JavaScript and CSS and made a test project in Visual Studio 2015 Community Edition. The problem that I have is, the function changeTitleCSSStyle isn't called when using Visual Studio 2015 Community Edition. At online editor https://js.do/ and in Google Chrome browser the function call works properly. My code:
index.htm
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/default.css">
<title>JavaScript and HTML</title>
<meta charset="utf-8" />
<script>
function changeTitleCSSStyle() {
alert("Aanroep");
var title = document.querySelector("#mainTitle");
title.style.color = 'black';
title.style.backgroundColor = "yellow";
title.style.border = "5px dashed red";
}
</script>
</head>
<body>
<h1 id="mainTitle">My home page</h1>
<p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
<button onclick="javascript: changeTitleCSSStyle();">Change style</button>
</body>
</html>
default.css
h1 {
color: red;
background-color: lightGreen;
border: 12px solid violet;
padding: 5px;
border-radius: 15px;
text-align: center;
}
p, h1 {
font-family: cursive;
}
p, img, button {
margin-left: 50px;
}
Not sure why it doesn't work when using VS. Maybe inline click events are not supported for some reason.
Perhaps it works if you try setting the event in your script itself like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript and HTML</title>
<meta charset="utf-8" />
<script>
function changeTitleCSSStyle() {
alert("Aanroep");
var title = document.querySelector("#mainTitle");
title.style.color = 'black';
title.style.backgroundColor = "yellow";
title.style.border = "5px dashed red";
}
document.addEventListener("DOMContentLoaded", function(event) {
var button = document.getElementById('change_style_button')
button.addEventListener('click', function(){
changeTitleCSSStyle()
});
});
</script>
</head>
<body>
<h1 id="mainTitle">My home page</h1>
<p>This is an example of interactivity between JavaScript and the HTML content of a document.</p>
<button id="change_style_button">Change style</button>
</body>
</html>
You can try
<button onclick="changeTitleCSSStyle();">Change style</button>

How to display javascript variables

I have looked up a question on the website (How to display javascript variables in a html page without document.write)
But when executing it in my own coding program it does not work. Hope you can help out!
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset ="UTF-8">
<meta name="viewport" content="width=device-width">
<style type="text/css">
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
</style>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
<script>
//https://stackoverflow.com/questions/9689109/how-to-display-javascript-variables-in-a-html-page-without-document-write
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event)){
$jsValue.innerHTML = $jsName.value;
}, false);
</script>
</body>
</html>
Because you have syntax error.. check the console.
Correct code should be:
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);

Integrate Datatables plugin with the help of D3.js

I've been on this for hours - I can't figure out which part of my code that is wrong.I managed to make and display a proper table when I run my code but I want to be able to make my table like this - http://www.codeproject.com/Articles/194916/Enhancing-HTML-tables-using-a-JQuery-DataTables-pl#Introduction
So I try using Datatable jquery plugin. So far no luck. Please, I would greatly appreciate your help.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.5/css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript" language="javascript" src="http://cdn.datatables.net/1.10.5/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id="container"></div>
<script type="text/javascript"charset="utf-8">
d3.text("file.csv", function (datasetText) {
var rows = d3.csv.parseRows(datasetText);
var tbl = d3.select("#container")
.append("table")
.attr("id","tableID");
// headers
tbl.append("thead").append("tr")
.selectAll("th")
.data(rows[0])
.enter().append("th")
.text(function(d) {
return d;
});
// data
tbl.append("tbody")
.selectAll("tr").data(rows.slice(1))
.enter().append("tr")
.selectAll("td")
.data(function(d){return d;})
.enter().append("td")
.text(function(d){return d;})
});
$(document).ready(function() {
$('#tableID').dataTable();
} );
</script>
</body>
<html>
Look at the browser console for any errors and mention them here, if you can't interpret them by yourself. It says that the dataTables function is unknown, which is caused by the fact, that you include two different jquery versions. I'm guessing the 2nd include of jquery replaces the inital namespace with the dataTables plugin defined.
The dataTables plugin should not be called outside the CSVs callback function. If loading the csv & execution the callback takes too long, the $('#tableID').dataTable(); is called before the DOM is even there. Move it inside the callback.
$(document).ready(function() {
d3.text("file.csv", function (datasetText) {
// draw d3 elements
$('#tableID').dataTable();
});
});

Understanding 'parentNode' of undefined error

I'm practicing basic JS skills by setting up little exercises for myself. In this one, I have a list of <a>s inside a div. The aim of the exercise is to wrap each <a> in a div. I'm using replaceChild in this instance.
Oddly (to me at least) the script works for the first three links, but after that throws an error:
Uncaught TypeError: Cannot read property 'parentNode' of undefined
I can't tell why the script partly works. Can anyone see what I'm doing wrong here? Here's the code I'm using:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
for (var i=0, ii=links.length; i<ii; i++)
{
var container = document.createElement("div");
links[i].parentNode.replaceChild(container, links[i]);
container.appendChild(links[i]);
}
</script>
</body>
</html>
and here's an online version: http://codepen.io/anon/pen/Lpuky
I've tried the few debugging techniques that I know of and read about this error message, but haven't worked out what's wrong here. Seems funny to me that it works for 3 of the 6 links.
The collection links is NodeList and is live.
Since you are replacing them, they are disappearing from the collection and our index into them is no longer pointing to anything.
You're modifying the nodelist as you iterate over it. Use the Array slice method to make a copy of the list:
var linksCopy = Array.prototype.slice.call(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
Regarding your own follow-up answer: if your objective was simply to find the easiest way to wrap the <a>s in <div>s, rather than to practice with createElement, replaceChild or appendChild or any of the other methods, this would be it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
div div {
padding: 10px;
background: #e7e7e7;
margin: 5px;
}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.querySelectorAll("a");
for (var i=0; i<links.length; i++) {
links[i].outerHTML = '<div>'+links[i].outerHTML+'</div>';
}
</script>
</body>
</html>
.
Live demo here: http://jsbin.com/jasoho/1/edit?html,output. Another advantage of the outerHTML method is that it doesn't change the nodeList. So you can also use getElementsByTagName in stead of querySelectorAll.
As a follow up to this, I often hear that querySelectorAll() is different in that it returns a static Nodelist rather than an array, so I thought that might come in handy here, and indeed it does:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.querySelectorAll("a");
for (var i=0, ii=links.length; i<ii; i++)
{
var container = document.createElement("div");
links[i].parentNode.replaceChild(container, links[i]);
container.appendChild(links[i]);
}
</script>
</body>
</html>
Also, an alternative to Array.prototype.slice.call(links) is [].slice.call(links):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = [].slice.call(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>
And another option again is to use [].forEach.call():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
[].forEach.call(document.querySelectorAll('a'), function(el) {
var container = document.createElement("div");
el.parentNode.replaceChild(container, el);
container.appendChild(el);
});
</script>
</body>
</html>
Yet another option, using Array.from():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
link
link
link
link
link
link
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = Array.from(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>

Categories

Resources