In below code I am trying to create two HTML dynamic tables, but it doesn't work.
One table with ID "Table" and another one with ID "Tabled".
<script type="text/javascript">
function Upload() {
const columns = [0, 3] // represents allowed column 1 and 3 in index form
const dccolumns = [0, 3] // represents allowed column 1 and 3 in index form
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
table.id = 'table'
var tabledc = document.createElement("tabled");
tabled.id = 'tabled'
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
// ignore columns that are not allowed
if (!columns.includes(j)) {
continue
}
var rc = cells[j];
if (rc == "SUMMARY") {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
alert(rc);
}
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
var alld = document.getElementById("alld");
alld.innerHTML = "";
alld.appendChild(tabled);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
When I run above code it just updates table in "Table", but not in "Tabled". I am not sure what wrong I am doing here.
Thanks
Related
I want to make product catalog, suppose 1-4 products in a row, and each product will be in a box with its details and price mentioned. I would like to be able to easily create the catalog based on a XML/CSV File which I can update.. Can any one point me in the right direction on how to achieve it. I am currently familiar with HTML/CSS.. I can pick up on Javascript if required.
Once finished the page will have a header, and then products displayed below.. I intend to print the page to PDF to share with other users..
First of all you should read your file and load from javascript.
Then once loaded, you parse it into JSON object
After this, you can preview the contents inside the HTML
(this is important because we'll use this html table to generate the pdf)
Using the library jsPDF and it's plugin AutoTable we generate a pdf file with the HTML table we generated previously.
This are the sample CSV file I used to test the example
Product,Price,Barcode
Sample product 1,100,802760000926
Sample product 2,95,802760000926
Sample product 3,20,802760000926
You can try it in my fiddle:
https://jsfiddle.net/rogeliomonter/2f9m0qse/
let myList = {};
/*Function to load from CSV file*/
function openFile(event) {
var input = event.target;
var node = document.getElementById('output');
node.innerText = '';
var reader = new FileReader();
reader.onload = function () {
text = reader.result;
//set to myList variable to be used later
myList = JSON.parse(csvJSON(reader.result));
buildHtmlTable('#output');
};
reader.readAsText(input.files[0]);
};
/*this function generates the HTML table*/
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
/*Supports the function that generates the HTML table*/
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
/*Converts CSV values into JSON object*/
function csvJSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
/*Uses jsPDF libary to generate a PDF File from the HTML table*/
function download() {
// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();
doc.text("My List", 10, 10);
var columns = ["Product", "Price", "Barcode"];
//Here we use the id of the table
doc.autoTable({ html: '#output' })
doc.save("myList.pdf");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>
<input type='file' accept='text/csv' onchange='openFile(event)'>
<br>
<!-- the HTML table that will have the csv table -->
<table id='output' border="1"></table>
<br>
<button onclick="download()">Generate PDF</button>
I am trying to count the number of rows between two rows containing particular words in google sheets. But I am getting the following error:
Cannot convert [object Object] to (class). (line 41, file "Code")
I have written the following code on the google app script:
function search(SPREADSHEET_ID, SHEET_NAME, word) {
var locatedCells = [];
var ss = SpreadsheetApp.openById(SPREADSHEET_ID);
var searchLocation = ss.getSheetByName(SHEET_NAME).getDataRange().getValues();
//Loops to find the search term.
for (var j = 0, jLen = searchLocation.length; j < jLen; j++) {
for (var k = 0, kLen = searchLocation.length; k < kLen; k++) {
var find = word;
if (find == searchLocation[j][k]) {
locatedCells.push({ 'found': (j + 1)});
}
}
}
// Logger.log(locatedCells);
return(locatedCells)
}
function footerlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Footers"
var footerlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(footerlocation);
return(footerlocation)
}
function keywordlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Keyword Page Redirects to Implement"
var keywordlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(keywordlocation);
return(keywordlocation)
}
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()
var endrow= keywordlocation()
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}
I would appreciate if someone could help me with this.
I was able to figure out the solution, change the count function to the following:
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()[0]['found']
var endrow= keywordlocation()[0]['found']
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}
I am running into a problem here. I parse a .CSV file and I need to show them into a DataTables format.
The problem is The markups are all inside javascript as shown below
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='comp-monitor' class='table table-condensed table-striped'> \n\
<tr><th>No.</th><th>DESKRIPSI ASSEMBLY</th><th>Drawing No.</th><th>QTY3</th><th>WEIGHT</th><th>-</th></tr>");
var rows = e.target.result.split("\n");
var no = 0;
for (var i = 0; i < rows.length; i++) {
no++;
// console.log(i);
var row = $("<tr />");
var cells = rows[i].split(",");
// Column No
var cell_no = $("<td />");
cell_no.html(no);
row.append(cell_no);
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
and the jquery initialization is just outside that function
$('#comp-monitor').DataTable();
Somehow the datatables doesn't run and I need some help with this where to put the initialization.
Thanks a bunch,
You can Initialize the datatable inside javascript itself
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='comp-monitor' class='table table-condensed table-striped'> \n\
<tr><th>No.</th><th>DESKRIPSI ASSEMBLY</th><th>Drawing No.</th> <th>QTY3</th><th>WEIGHT</th><th>-</th></tr>");
var rows = e.target.result.split("\n");
var no = 0;
for (var i = 0; i < rows.length; i++) {
no++;
// console.log(i);
var row = $("<tr />");
var cells = rows[i].split(",");
// Column No
var cell_no = $("<td />");
cell_no.html(no);
row.append(cell_no);
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
//HERE
$('#comp-monitor').DataTable();
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
let me know if this work.
I found an answer by using addrow
var t = $('#comp-monitor').DataTable({
});
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("#comp-monitor tbody");
var rows = e.target.result.split("\n");
var no = 0;
table.empty();
for (var i = 0; i < rows.length; i++) {
no++;
var row = $("<tr class='odd' role='row' />");
var cells = rows[i].split(",");
t.row.add([
no,
cells[0],
cells[1],
cells[2],
cells[3],
cells[4]
]).draw(false);
table.append(row);
}
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
I've uploaded a CSV-file to an HTML page via javascript. The CSV rows are: name and email-address, e.g. rambo,rambo#rambo.com.
How to SEARCH the 'name' from these loaded CSV-file?
Also, one of the data is an email-address and I want to send a mail to that email-address. Is that value retrieved to a variable?
My code to search each elements:
function Search() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for(var j = 0; j < cells.length; j++)
{
var cell = row.insertCell(-1);
// cell.innerHTML = cells[j];
// Here repeated checkboxes:
var radio = document.createElement('input');
radio.type = 'checkbox';
radio.name = 'check';
}
var ser=document.getElementById("texts");
if(cells[i].indexOf(ser))
{
alert("matches");
cell.innerHTML = cells[i];
}
else
{
alert("unmatches");
}
var cell = row.insertCell(-1);
cell.appendChild(radio);
//cell.appendChild(button);
}
var button = document.createElement('button');
button.textContent = 'Send';
cell.appendChild(button);
button.onclick = function(){ alert();};
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
}
}
}
Ad search: indexOf() is your friend here. This should give you a figure:
var table = $('#your-table'),
searchstring = 'your-searchstring';
searchstring.toLowerCase();
for (var i = 0, cell; cell = table.cells[i]; i++) {
if (cell.indexOf(searchstring)) {
// I don't know what you want to do with the search-results...
// ..but you can do it here.
}
}
Ad email-address: you can add the address to a variable in your CSV-import:
var cells = rows[i].split(","),
address = cells[1];
I'd suggest making an array addresses and fill it each row.
I have a table where I can add images onclick. The table is created dynamically from a form. I have tried to save the table to local storage, but I am getting a circular reference issue. I have read this Example of a circular reference in Javascript? but I am a complete novice and struggling to understand. Can you point it out to me?
function makeChart() {
var table = document.createElement('table'),
taskName = document.getElementById('taskname').value,
header = document.createElement('th'),
numDays = document.getElementById('days').value, //columns
howOften = document.getElementById('times').value, //rows
row,
r,
col,
c;
var cel = null;
var myImages = new Array();
myImages[0] = "http://www.olsug.org/wiki/images/9/95/Tux-small.png";
myImages[1] = "http://a2.twimg.com/profile_images/1139237954/just-logo_normal.png";
var my_div = document.createElement("div");
my_div.id = "showPics";
document.body.appendChild(my_div);
var newList = document.createElement("ul");
my_div.appendChild(newList);
if (taskName == '' || numDays == '') {
alert('Please enter task name and number of days');
}
if (howOften == '') {
howOften = 1;
}
if (taskName != '' && numDays != '') {
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
allImages.onclick = function (e) {
if (sel !== null) {
sel.src = e.target.src;
my_div.style.display = 'none';
sel.onclick = null;
sel = null;
}
};
var li = document.createElement('ul');
li.appendChild(allImages);
newList.appendChild(li);
}
my_div.style.display = 'none';
header.innerHTML = taskName;
table.appendChild(header);
function addImage(col) {
var img = new Image();
img.src = "http://cdn.sstatic.net/stackoverflow/img/tag-adobe.png";
col.appendChild(img);
img.onclick = function () {
my_div.style.display = 'block';
sel = img;
};
}
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
}
}
document.getElementById('holdTable').appendChild(table);
document.getElementById('createChart').onclick = null;
console.log(table);
localStorage.setItem(name, JSON.stringify(table));
console.log( JSON.parse( localStorage.getItem( table ) ) );
}
}
Any DOM element holds a reference to the parentNode and to the document, which you can't stringify. In fact each element holds a link to it parent which holds links to its childs.
You can't apply JSON.stringify to a DOM element.
If you really want to save your table, you could save its HTML using table.innerHTML. We could propose other solutions (there even are specific stringify implementations able to produce JSON from circular elements or DOM nodes). But we'd need to know why you try to save a table in localStorage.