I have some Javascript code that reads a published Google Sheet and reads it to the webpage. For some reason upon embedding this int Weebly, it just doesn't want to take it. No elements are created at all as far as i can tell. Here is my code, any help is awesome.
<!DOCTYPE html><!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function readData(parent) {
var data = spData;
var ScoreObjs = [];
var ScoreObj = new Object();
for(var r=4; r < data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
console.log(val);
if (cell.col == 1) {
ScoreObj.team1 = val;
}
else if (cell.col == 2) {
ScoreObj.team2 = val;
}
else if (cell.col == 3) {
ScoreObj.score1 = val;
}
else if (cell.col == 4) {
ScoreObj.score2 = val;
ScoreObjs.push(ScoreObj);
ScoreObj = new Object();
}
}
toFormat(ScoreObjs);
}
function toFormat(obj) {
for (var x = 0; x < obj.length; x++)
{
var data = obj[x];
var team1 = data.team1;
var team2 = data.team2;
var score1 = data.score1.toString();
var score2 = data.score2.toString();
var child1 = document.createElement("div");
child1.className = "paragraph";
document.body.appendChild(child1);
var child2 = document.createElement("strong");
child1.appendChild(child2);
var child3 = document.createElement("font");
child3.color = "#FFFFFF";
child3.innerHTML = team1 + " vs " + team2 + "<br />ESEA Scrim";
child2.appendChild(child3);
var child4 = document.createElement("font");
child4.color = "#00FF00";
child4.innerHTML = score1 + ":" + score2;
child1.appendChild(child4);
}
}
$(document).ready(function(){
readData($("#data"));
});
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
</head>
</html>
Change:
<script
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
To:
<script id="data"
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
This could be because the javascript code runs first and renders some problems. I had the same problem.
Include script tags in the footer and not in the head section.
In fact you will find default Weebly script tags below the footer. Add your custom javascript code along with that.
OR
(MORE PREFERABLE)
Create a javascript(.js) file externally upload it to Assets in weebly theme editor and then add it to your HTML header file along with other default weebly script tags.
eg. a javascript file named editsite.js will be added like this (after uploading to assets):
<script type="text/javascript" src="/files/theme/editsite.js"></script>
Related
I am working on a project where I call a certain API and in response I get back a json string with all the information. I need to find a way using javascript to display this json string into a table format. I got a very basic version of this running. However, the problem I am having is that I cannot find a way to display a image in this block of code.
results.html file:
<!DOCTYPE HTML>
<html>
<head>
<title>
How to convert JSON data to a
html table using JavaScript ?
</title>
<h1>Results: </h1>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;" id = "body">
<h3>Showing resuls for: {{searchQuery}}</h3>
<p>{{responseText}}</p>
<br><br>
<table align = "center"
id="table" border="1">
</table>
<div id="header"></div>
<script>
var el_up = document.getElementById("GFG_UP");
var list = [];
list = "{{responseText|escapejs}}";
//console.log(list);
var titles = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 't' && list[i+1] == 'i')
{
var title = '';
for(var j = (i+8); list[j] != ","; j++) {
title += list[j];
}
i = j;
console.log(title + ", ")
titles.push(title)
}
}
console.log(titles)
var images = []
for (var i = 0; i < list.length-8; i++) {
if(list[i] == 'h' && list[i+1] == 't')
{
var image = '';
for(var j = (i); list[j] != ","; j++) {
image += list[j];
}
i = j;
console.log(image + ", ");
var img = new Image();
img.src = image.slice(0, -1);
images.push(img);
}
}
console.log(images)
var restaurants = []
for (var i = 0; i < list.length-17; i++) {
if(list[i] == 'r' && list[i+1] == 'e' && list[i+2] == 's')
{
var restaurant = '';
for(var j = (i+17); list[j] != ","; j++) {
restaurant += list[j];
}
i = j;
console.log(restaurant + ", ")
restaurants.push(restaurant)
}
}
console.log(restaurants)
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
console.log(typeof(cellData))
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
})
table.appendChild(tableBody);
document.body.appendChild(table);
};
var a = [titles, restaurants, images]
console.log(a)
createTable(a);
</script>
</body>
</html>
The function createTable is the one in question. It displays the text parts correctly. Im not sure how to get it to display images given the URLs of those images in a table.
output HTML file:
HTML output
You should show us the API response you are working with here.
Another thing is your createTable function expects to get table data. But onclick on your button pass there #table ID. Not sure if it should be like this.
Also you could run your JS script when all page is loaded:
window.onload = () => {
// Your JS script which should do something after page is loaded.
}
Finally it comes to the images. I think that you are not using img tag anywhere so your images simply won't be visible in the table. If you would like to see them just create img element and put it into td.
Few advices (not related with your question):
stop using console.log so much, place debugger statement in your code and debug it like a pro, if you don't know how just look for it in youtube,
please put your attention to a code style, it is a bit messy, if you have real trouble with it use ESlint to fix it for you.
EDIT
About images - if you want to create DOM element for img use code below instead of current one:
var img = document.createElement("IMG");
Than you can set src and other things like alt and so on:
img.src = imgUrlString;
I am developing a chrome extension that can copy the urls of all tabs in a browser. The problem is i can only trim one url in all the array. Is there a way i can output all the root domain in the popup?thanks in advance
example of the tabs url
youtube.com/asdwea/asdsa
google.com/asdwew
facebook.com/qwea/asd
the result for the popup should be
youtube.com
google.com
facebook.com
popup.html
<html>
<script src="popup.js"></script>
<body>
<div id="result"></div>
<div id="count"> all</div>
</body>
</html>
popup.js
chrome.windows.getAll({populate:true}, getAllOpenWindows);
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
for (var j=0; j<totTabs;j++) {
tabs.push(winTabs[j].url+ "</br>");
}
var domain = tabs[1].replace('http://','').replace('https://','').split(/[/?#]/)[0];
}
}
document.getElementById('count').innerHTML = tabs.length;
document.getElementById('result').innerHTML = domain;
}
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var domainStr = "";
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
for (var j=0; j<totTabs;j++) {
var str = winTabs[j].url+ "</br>";
tabs.push(str);
domainStr += str;
}
domainStr = domainStr.replace('http://','').replace('https://','').split(/[/?#]/)[0];
}
}
document.getElementById('count').innerHTML = tabs.length;
document.getElementById('result').innerHTML = domainStr;
}
I think what you need is concat all strings, which is domainStr here.
As your question is not related to split function, I did not check whether .replace('http://','').replace('https://','').split(/[/?#]/)[0]; works.
I am trying to create a score keeper display.
I want to keep track of the score using html and javascript. I have everything figured out I think but I can't figure out why the line doesn't break here.
Relevant code:
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br);
scorechart.appendChild(tot);
}
(For a full view: https://hastebin.com/osuduluvaj.js)
It breaks for everything but the "------" part: https://media.discordapp.net/attachments/240883852350980096/497957073481629696/sAAAAASUVORK5CYII.png
(I cant upload images yet as a new member)
Thank you :)
document.createElement() creates a single element, which you can only append to the DOM once. If you want to reuse the <br> element you created, you need to clone it and you can insert the cloned copy into the DOM. See: Node.cloneNode().
var score = [];
var scoreadd_button = document.querySelector('#scoreadd-button');
var scoreadd_input = document.querySelector('#scoreadd-input');
let sc1 = 0;
let sc2 = 0;
var scorechart = document.querySelector('.scores');
function totalScores() {
var i;
var sum = 0;
for (i = 0; i < score.length; i++) {
sum += score[i];
}
return sum;
}
function newScore(amm) {
score.push(amm);
if (!score[1]) {
var nc = document.createTextNode(amm)
} else {
var nc = document.createTextNode(" + " + amm);
}
if (sc1 == 0) {
sc1 = amm;
} else {
sc2 = amm;
}
if (sc2 != 0) {
var tot = document.createTextNode("= " + totalScores());
sc1 = amm;
sc2 = 0;
}
var br = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(nc);
if (tot) {
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(nes);
scorechart.appendChild(br.cloneNode(true));
scorechart.appendChild(tot);
}
}
scoreadd_button.addEventListener('click', function() {
var amm = scoreadd_input.value;
newScore(parseInt(amm, 10));
});
<button id="scoreadd-button">button</button>
<input type="text" id="scoreadd-input" />
<div class="scores"></div>
Okay so I fixed the issue by instead of using a variable just creating the element in the statement.
var nes = document.createTextNode("---------");
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nc);
if(tot) {
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(nes);
scorechart.appendChild(document.createElement("br"));
scorechart.appendChild(tot);
}
Thank you :)
You just need to defined unique variables for each new created element on javascript, otherwise they will counted as one.
This code should works
var scorechart = document.querySelector('.scores');
var br = document.createElement("br");
var br2 = document.createElement("br");
var nes = document.createTextNode("---------");
scorechart.appendChild(br);
scorechart.appendChild(nes);
scorechart.appendChild(br2);
<span class="scores">
text before
</span>
after text
I am working on a check-in app though Google Sheets and want to make a search function that that takes a sport name as input in an HTML form and then returns information about the sport from the sheet in a HTML table. However, when I try to test the web app, nothing happens. How can I fix this?
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<fieldset id="tasks-panel">
<legend>Sports</legend>
<form name="sport-form" id="sport-form">
<label for="sport-name">Search a sport by name:</label>
<input type="text" name="sport-name" id="sport-name" />
<button onclick='addTable()' id='submit-button'>Press this</button>
</form>
<p>List of things:</p>
<div id="toggle" style="display:none"></div>
</fieldset>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<script>
function addTable() {
var sportInput = $('sport-name').value();
var columnNames = ["Names", "Times"];
var dataArray = google.script.run.getSportData(sportInput);
var myTable = document.createElement('table');
$('#divResults').append(myTable);
var y = document.createElement('tr');
myTable.appendChild(y);
for(var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for(var i = 0 ; i < dataArray.length ; i++) {
var row= dataArray[i];
var y2 = document.createElement('tr');
for(var j = 0 ; j < row.length ; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
}
</script>
Code.gs
//Setting up global variables
var ss = SpreadsheetApp.openById("-spreadsheetID-");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
var OUTPUT = [];
//doGet function
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle('Check In Data')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Gets both names and times of checked-in people
function getSportData(input) {
var sportInput = input;
getNamesInSport(sportInput);
getTimesInSport(sportInput);
OUTPUT = [
[NAMES],
[TIMES]
];
Logger.log(OUTPUT);
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
JQuery id selectors must be prefixed with # so to grab the value from the the 'sport-name' input you'll need to select it using
var sportInput = $('#sport-name').val();
Additionally, as Robin comments above, if you want to use the JQuery library you'll need to load it, the code you've shown indicates you might not have done this?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
Although if this were the case you'd probably be seeing a '$ is not defined' error straight away.
Essentially I am return an array of values that will either be " " or "X". When It's "X" I would like the element to be shown (which it is on page load), and when it's " "(blank) I'd like the element to be given
style.display = 'none';
Here is my Script so far:
<script type="text/javascript">
function onSuccess(id) {
for(var i = 0; i < 100; i++) {
if (id[i] == '') {
var td_mod = document.getElementById(i);
td_mod.style.display = 'none';
}
}
}
google.script.run.withSuccessHandler(onSuccess).returnAch();
</script>
And here is the function "returnAch();"
function returnAch() {
//return the ARRAY of all 'X'
var sheet = SpreadsheetApp.getActive().getSheetByName('Achievements');
var value = sheet.getRange("E1:E100").getValues();
//Logger.log(value + "<--- Values of 'x'");
return value;
}
I've tested "returnAch()" and it logs the entire array of values - I'm just unsure which part of the HTML I'm messing up.
Thanks for any and all help!
Okay so I figured out I wasn't calling the GoogleScript Function Correctly,
Html / Javascript:
<script type="text/javascript">
function onSuccess(id) {
for(var i = 1; i < 100; i++) {
if (id[i] == '') {
var td_mod = document.getElementById(i-1);
td_mod.style.display = 'none';
console.log(td_mod);
}
}
}
google.script.run.withSuccessHandler(onSuccess).returnAch();
</script>
Google Script:
function returnAch() {
//on call return if there is an x at pos "loc"
//return the ARRAY of all 'X'
var value = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName("Achievements").getRange("E1:E100").getValues();
//Logger.log(value + "<--- Values of 'x'");
return value;
}