how to create "href" using JavaScript of a google drive file - javascript

I have a dynamic table created using JavaScript my dataArray consist of many information including drive file downloadable link example :-
dataArray[i][4] has google file dowanload link = drive.google.com/uc?export=download&id=1YH6xxxxxxxxxxxxxxxphUl
Now I can't create a downloadable link using the url field of my dataset I tried following:-
function getreferData(dataArray)
{
var ray = dataArray.splice(0,1)
let table = document.getElementById('thead1');
var tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for(i=0;i<ray[0].length;i++){
var tableHeader = document.createElement("th");
tableHeaderRow.appendChild(tableHeader);
tableHeader.innerHTML = ray[0][i];
}
let tbody = document.getElementById('perf');
for (var i=0;i<dataArray.length;i++)
{
let row = document.createElement("tr")
for (var j=0;j<dataArray[i].length;j++)
{
if (j==4)
{
let col = document.createElement("td")
var a = document.createElement("a");
a.href = "/'"+dataArray[i][j]+"/'";
var node = document.createTextNode("Click here")
a.appendChild(node)
col.appendChild(a)
row.appendChild(col)
}
else
{
let col = document.createElement("td")
col.innerText = dataArray[i][j]
row.appendChild(col)
}
}
tbody.appendChild(row);
}
image of my array logs:-

I was able to get it worked by Adding "https://" in my link drive.google.com/uc?export=download&id=1YH6xxxxxxxxxxxxxxxphUl.

Related

How to fetch table data which is currently present on screen using javascript and convert it into csv file

after applying filter in table there are 4 enteries present.How can we store this data and convert it into csv.Currently i am able to dowload full table data using python code.But now i want to fetch and dowload the csv of data which is present on the screen.
========================================================================
function getTableDataFn() {
//we can use any of the get methods based on what we want
let reqTable = document.getElementById("tableId");
//Get rows
let rows = reqTable.rows.length;
//Get columns
let columns = 0;
if (rows > 0)
columns = reqTable.rows[0].cells.length;
let dataInArray = [];
let strVersionOfData = ``;
//Loop through row and column to get data in the object
for (let r = 0; r < rows; r++) {
dataInArray[r] = [];
for (let c = 0; c < columns; c++) {
let tempData = reqTable.rows[r].cells[c].innerHTML;
dataInArray[r][c] = tempData;
strVersionOfData += tempData;
if (c != columns - 1)
strVersionOfData += ",";
}
strVersionOfData += "\n";
}
//Now the dataInArray has all the data and
//strVersionofData has the string
downloadCSVStringFn(strVersionOfData,'mycsv');
}
The above mentioned code might help you to get the data in array and string format. Now if you want to get your csv content downloaded in a file with name you can go by below mentioned function
function downloadCSVStringFn(fileName = "", csvString = "") {
//Encode CSV data
var encodedUri = encodeURI(csvString);
//Create link
var link = document.createElement("a");
//set attributes
link.setAttribute("href", encodedUri);
link.setAttribute("download", fileName + ".csv");
//Append in document
document.body.appendChild(link); // Required for FF
//Click .. this will download
link.click();
//you can further delete the link too .. or have this is a component in case
//you have download as a reusable utility
}

Java Script: TypeError: Cannot read property 'createTHead' of null, while printing table dynamically

I am a beginner at coding and I am trying to print a table dynamically in my HTML file. The following error appears: "Uncaught TypeError: Cannot read property 'createTHead' of null
at generateTableHead3", where generateTableHead3 is my calling of function to print the header.
I have been trying to understand why this is happening to absolutely no avail for the last 4 hours.
I have other printed tables dynamically, and they all work. This code is copy-pasted from the original table which prints perfectly on the HTML, and so do other 2 tables created in the same JS file. And then, the third one doesn't. I created a separate html and js to test, and it still returns the error. What am I missing?
let header3 = ["Name", "No. Party", "% Party Votes"];
function generateTableHead3(table, array) {
let thead = table.createTHead();
let row = thead.insertRow(0);
for (i = 0; i < array.length; i++) {
let cell = document.createElement("th");
cell.innerHTML = array[i];
row.appendChild(cell);
}
}
function generateTable3(table, data) {
for (let element of data) {
let row = table.insertRow();
let cell1 = row.insertCell();
let a = document.createElement('a');
let link = document.createTextNode(element['first_name'] + ' ' + (element['middle_name'] || '') + ' ' + element['last_name']);
a.appendChild(link);
a.href = element.url;
a.title = link;
document.body.appendChild(a);
cell1.appendChild(a);
}
}
let table3 = document.getElementById("least-loyal");
let data3 = Object.keys(array10LeastLoyal);
generateTableHead3(table3, header3);
generateTable3(table3, array10LeastLoyal);

Avoid display duplicate elements in table

So I saved some data in localStorage.
I get them back from localstorage to the table.
When I click on the button to enter new data, the data entered earlier is duplicated in the table. When I refresh the page, everything is fine.
$(document).ready(function() {
function save() {
list.forEach(function(item) {
var nameNode = document.createTextNode(item.name);
var surnameNode = document.createTextNode(item.surname);
var dataNode = document.createTextNode(item.data);
var nrNode = document.createTextNode(item.nr);
var tdName = document.createElement("td");
var tdSurname = document.createElement("td");
var tdData = document.createElement("td");
var tdNr = document.createElement("td");
tdName.appendChild(nameNode);
tdSurname.appendChild(surnameNode);
tdData.appendChild(dataNode);
tdNr.appendChild(nrNode);
var tr = document.createElement("tr");
tr.appendChild(tdName);
tr.appendChild(tdSurname);
tr.appendChild(tdData);
tr.appendChild(tdNr);
// download table and insert cells and rows
var table = document.getElementById("table");
table.appendChild(tr);
});
}
list = jQuery.parseJSON(localStorage.getItem("osoba") === null ? [] : localStorage.getItem("osoba"));
save();
$("#send").click(function() {
var osoba = {};
osoba["name"] = document.getElementById("name").value;
osoba["surname"] = document.getElementById("subname").value;
osoba["data"] = document.getElementById("date_bth").value;
osoba["nr"] = document.getElementById("numer_phone").value;
list.push(osoba);
localStorage.setItem("osoba", JSON.stringify(list));
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("date_bth").value = "";
document.getElementById("numer_phone").value = "";
save();
});
});
How to avoid duplication in the table without reloading the page?
When you save, you need to first clear the data already on the table or it will be added to it again when you call save. Here's how you do that:
$(document).ready(function(){
function save() {
$("#table tr").remove(); // <- this
list.forEach(function (item) {
var nameNode = document.createTextNode(item.name);
var surnameNode = document.createTextNode(item.surname);
var dataNode = document.createTextNode(item.data);
var nrNode = document.createTextNode(item.nr);
var tdName = document.createElement("td");
var tdSurname = document.createElement("td");
var tdData = document.createElement("td");
var tdNr = document.createElement("td");
tdName.appendChild(nameNode);
tdSurname.appendChild(surnameNode);
tdData.appendChild(dataNode);
tdNr.appendChild(nrNode);
var tr =document.createElement("tr");
tr.appendChild(tdName);
tr.appendChild(tdSurname);
tr.appendChild(tdData);
tr.appendChild(tdNr);
// download table and insert cells and rows
var table = document.getElementById("table");
table.appendChild(tr);
});
}
list = jQuery.parseJSON(localStorage.getItem("osoba") === null ? [] : localStorage.getItem("osoba"));
save();
$("#send").click(function(){
var osoba = {};
osoba["name"] = document.getElementById("name").value;
osoba["surname"] = document.getElementById("subname").value;
osoba["data"] = document.getElementById("date_bth").value;
osoba["nr"] = document.getElementById("numer_phone").value;
list.push(osoba);
localStorage.setItem("osoba",JSON.stringify(list));
document.getElementById("name").value="";
document.getElementById("surname").value="";
document.getElementById("date_bth").value="";
document.getElementById("numer_phone").value="";
save();
});
});

Firebase - Generate table from database data

I would like to know how to create a table like thisfrom some data in a firebase database like this
There would need to be a column for ID, Title, Number of Answers, Correct Answer and Type. Preferably this should be done using jQuery.
Thank you in advance.
Get data
Read the firebase database documentation and references.
The basic firebase read operation looks like this:
var ref = firebase.database().ref("location");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key;
var value = snapshot.val();
console.log(key + ": " + value);
});
Of course you have to add scripts for firebase and firebase database before.
If you want to loop through an data you can use forEach function, for example:
var query = firebase.database().ref("location2");
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var value = childSnapshot.val();
console.log(key + ": " + value);
});
});
Table
You can create table dynamically using JS - functions like createElement and createDocumentFragment
For example:
var fragment = document.createDocumentFragment();
var animalsArray = ["Elephant", "Dog", "Cat"];
var table = document.createElement("table");
for (var i = 0; i < animalsArray.length; i++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
td.textContent = animalsArray[i];
tr.appendChild(td);
table.appendChild(tr);
}
fragment.appendChild(table);
document.body.appendChild(fragment);
Table built from data in Firebase database
And now connect concepts above together. Create a table. Get data from firebase database. At every ireration over this data: create new table row with cells built from key and value of an element. In example below I used for loop to not duplicate the same operation for every cell.
Full example:
Data tree in Firebase Database:
{
"location2" : {
"hello" : "world",
"hi" : "Mark"
}
}
Code:
var fragment = document.createDocumentFragment();
var table = document.createElement("table");
var query = firebase.database().ref("location2");
query.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var tr = document.createElement("tr");
var trValues = [childSnapshot.key, childSnapshot.val()];
for (var i = 0; i < trValues.length; i++) {
var td = document.createElement("td");
td.textContent = trValues[i];
tr.appendChild(td);
}
table.appendChild(tr);
});
});
fragment.appendChild(table);
document.body.appendChild(fragment);

Cannot create dynamically img via javascript

I try to create img element via javascript and set it into td element, but id doesn't work. I can't see any image or icon that img is not found. My server is running on localhost now so that's the reason for img url
function fillTable(actualMarkers){
// Get array of classes without jQuery
var theTable = document.createElement('table');
theTable.id = 'actualPlaces';
// Note, don't forget the var keyword!
for (var i = 0, tr, tdName, tdId, tdImage, imgPlace ; i < actualMarkers.length; i++) {
tr = document.createElement('tr');
tdId = document.createElement('td');
tdImage = document.createElement('td');
tdName = document.createElement('td');
imgPlace = document.createElement('img');
imgPlace.src = 'http://localhost:8080/webapp/images/var/webapp/photos/small/tuc.png';
imgPlace.height = '20';
imgPlace.width = '20';
var marker = actualMarkers[i];
tdId.appendChild(document.createTextNode(marker.get("id")));
tdId.className = 'unvisible';
tdImage.appendChild(imgPlace);
tdName.appendChild(document.createTextNode(marker.get("name")));
tr.appendChild(tdId);
tr.appendChild(tdImage);
tr.appendChild(tdName);
theTable.appendChild(tr);
}
document.getElementById('foundPlaces').appendChild(theTable);
addRowHandlers();
}
Usually the src attribute look like :
imgPlace.src = 'photos/small/tuc.png';
Try to change your images path, but I think it's very strange have two time "webapp" in your src url.

Categories