Integrate Datatables plugin with the help of D3.js - javascript

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();
});
});

Related

Setting color theme in Google Sheets sidebar via cell value

I would like the Google Sheets sidebar to open with a color set in cell Sheet1:A1. My current code works (I suspect there may be a more efficient way to do this), but the CSS steps through each theme in root until it lands on the correct theme.
For example, if A1 is set to 'Orange', calling the sidebar will load with the body first as 'Default' and then switch to 'Orange'. Is there a way to load the correct root theme on the initial page load instead of stepping through the themes in root?
Google Apps Script
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu("Sidebar")
.addItem("Show sidebar", "showSidebar")
.addToUi();
}
function showSidebar() {
var htmlWidget = HtmlService.createTemplateFromFile('Test').evaluate()
.setTitle("Theme Test");
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
function getColorTheme() {
colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
return colorTheme;
}
HTML for Sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
function setTheme(colorTheme) {
document.documentElement.className = colorTheme;
}
</script>
</head>
<body>
<p>Hello world</p>
<script>
google.script.run.withSuccessHandler(setTheme).getColorTheme();
</script>
</body>
</html>
From your situation, how about the following patterns?
Pattern 1:
In this pattern, HTML is modified using Google Apps Script and the modified HTML is used with HtmlService.createHtmlOutput().
Google Apps Script side:
function showSidebar() {
var colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
var html = HtmlService.createHtmlOutputFromFile('Test').getContent().replace("{{colorTheme}}", colorTheme);
var htmlWidget = HtmlService.createHtmlOutput(html).setTitle("Theme Test");
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
HTML side:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
document.documentElement.className = "{{colorTheme}}";
</script>
</head>
<body>
<p>Hello world</p>
</body>
</html>
Pattern 2:
In this pattern, HTML is modified using HTMl template and the modified HTML is used with HtmlService.createHtmlOutput().
Google Apps Script side:
function ashowSidebar() {
var colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
var htmlWidget = HtmlService.createTemplateFromFile('Test')
htmlWidget.colorTheme = colorTheme;
SpreadsheetApp.getUi().showSidebar(htmlWidget.evaluate().setTitle("Theme Test"));
}
HTML side:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
document.documentElement.className = "<?= colorTheme ?>";
</script>
</head>
<body>
<p>Hello world</p>
</body>
</html>
Note:
From the recent benchmark of the HTML template, it seems that in the current stage, the process cost of evaluate() is a bit high. Ref So, I proposed the above 2 patterns with and without an HTML template.
In this case, <html class="{{colorTheme}}"> and <html class="<?= colorTheme ?>"> might be able to be used instead of Javascript. But, I'm not sure about your actual situation. So, in this answer, Javascript is used as a sample modification.
References:
createHtmlOutput(html)
HTML Service: Templated HTML
createTemplateFromFile(filename)

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

display contents of csv file in html page

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 .

Javascript/JQuery for Datatables

Now I want to integrate the plugin Datatables using JQuery.
for example I can add this into my code above :
$("table#myTableId").dataTable();
If I take the ID of the table from the HTML source and call the dataTable() function, all the mentioned features will be automatically added and they will be fully functional. jQuery DataTables takes the plain HTML table and dynamically injects all elements,
I assign an id to my table I created above so that I can use the ID to call the datatable() later on.
I managed to add the ID but there's no change to my Table when I call the dataTable(). What did I do wrong?
<!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>
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<!-- <script src="d3.min.js"></script>-->
<script type="text/javascript"charset="utf-8">
d3.text("test.csv", function(data) {
var parsedCSV = d3.csv.parseRows(data);
var container = d3.select("body")
.append("table")
.attr("id", "custom_id")
.selectAll("tr")
.data(parsedCSV).enter()
.append("tr")
.selectAll("td")
.data(function(d) { return d; }).enter()
.append("td")
.text(function(d) { return d; });
});
$("#custom_id").dataTable();
</script>
</body>
<html>
Assign the id as you would assign any other attribute:
var container = d3.select("body")
.append("table")
.attr('id', 'custom_id');
Which leads to $('#custom_id').dataTable();

Javascript: How to check if button's click function is assigned

I know this question has been asked, but this is different from that question. I am trying to solve it with mere Javascript.
The problem relates to my backbone.js application, which I've brought down to the simplest form, yet can't get events to work. Any suggestion would be most appreciated.
My code:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Learning About Backbone.js Views</title>
<style type="text/css">
#container { padding:20px; border:1px solid #333; width:400px; }
#list-template { display:none; }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script type='text/javascript'>
var ListView=Backbone.View.extend({
initialize:function(){
console.log('initialized');
},
el:'body',
events:{
'click #add':'time',
'click':'whatApp'
},
time: function()
{
console.log('hooooooop');
},
whatApp:function()
{
console.log('Coool');
}
});
var listView = new ListView();
</script>
</head>
<body>
<button id='add'>Add list item</button>
</body>
</html>
Nothing wrong with what you are doing.
You are trying to initialize the view before the body (or the dom) is there.
You should initialize the view after the dom is loaded:
$(function(){
var listView = new ListView();
});
With jQuery, you should be able to use the Data API to view events and assigned functions:
$('#add').data('events')

Categories

Resources