Pass variable in Google Apps Scriptlet to javascript - javascript

I just started coding with HTML and scriptlets within Google Sheets.
Trying to pass the array variable teacherArrayLean from the scriptlet (enclosed by <? ... ?>) to the <script>. However, <script> doesn't read the variable; when I replace the variable with constants, the scripts runs no problem so I know it's not the rest of the code.
Does anyone know how to use the variable in <script>? Thank you!
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, td, th {border: 1px solid black;}
table {border-collapse: collapse;}
th {text-align: left;}
</style>
</head>
<body>
<? var querySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('query');
var teacherArrayRaw = querySheet
.getRange(2, 4, querySheet.getLastRow() - 1, 1)
.getValues();
teacherArrayRaw.sort();
var teacherArrayLean = [];
teacherArrayLean.push(teacherArrayRaw[0]);
for(var n in teacherArrayRaw) {
if(teacherArrayLean[teacherArrayLean.length-1].toString().trim() != teacherArrayRaw[n].toString().trim()) {
teacherArrayLean.push(teacherArrayRaw[n]);
}
}
?>
<table id="calendar"></table>
<script>
var teacherArrayLean = [];
var table = document.getElementById("calendar");
var row = table.insertRow(0);
for (var col = 0; col < teacherArrayLean.length; col++) {
var cell = row.insertCell(col);
cell.innerHTML = teacherArrayLean[col];
}
</script>
</body>
</html>

You can do something like this:
<script>
var teacherArrayLean = JSON.parse("<?=JSON.stringify(teacherArrayRaw)?>");
....
</script>

Related

Django updates view based on database

My issue seems pretty simple but I found it difficult since I'm extremely new to HTML / CSS / Django.
I have a postgresql database that is being updated continuously by another microservice. What I want to do is simply display the table in a HTML page (with https://datatables.net/ for example) and keep on updating it. I've found that we can create websocket connection when we reach the html page via channels but all the tutorial online are about chatbot.
I've managed to do it via a websocket/consumer:
class WSConsumer(WebsocketConsumer):
def connect(self):
self.accept()
while True:
#get the entire info from my db table
info = list(infoDB.objects.value())
self.send(json...(info..))
I keep on receiving the information in my HTML page (which is what I wanted), the only problem is I'm getting EVERYTHING from the table + I'm having hard time replacing correctly the initial table with the new one.
Here is my HTML page:
{% load static %}
<!DOCTYPE html>
<html lang="En">
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<title>Test</title>
</head>
<body>
<table id="table_id" class="table table-bordered" style="width:100%">
</table>
<script>
const socket = new WebSocket('ws://127.0.0.1:8000/ws/info_co/')
socket.onmessage = function(e){
const data = JSON.parse(e.data);
const table = document.getElementById("table_id");
for (var i = 0; i < data.message.length; i++)
{
var newRow = table.insertRow(table.length);
for (let key in data.message[i]){
var cell = newRow.insertCell(i);
cell.innerHTML = data.message[i][key];
}
}
var table = $('<table id="table_id" class="table table-bordered" style="width:100%">');
var tr = $('<tr>');
var arrheader = ['col 1', 'col 2', 'col 3','col 4', 'col 5','col 6'];
var array = data.message;
for (var j = 0; j < arrheader.length; j++) {
tr.append($('<th>').text(arrheader[j]));
}
table.append(tr);
for (var i = 0; i < array.length; i++) {
table.append(
$('<tr>').append(
$('<td>').text(array[i].elem_a),
$('<td>').text(array[i].elem_b),
$('<td>').text(array[i].elem_c),
$('<td>').text(array[i].elem_d),
$('<td>').text(array[i].elem_e),
$('<td style="color: green">').text(array[i].elem_f)
));
}
//table.css("border", "solid");
//document.querySelector('#table_id').innerHTML = table;
//document.getElementById('table_id').innerHTML = table;
$('#table_id').replaceWith(table);
//$('body').append(table);
}
$("#table_id").DataTable({
paging : true,
pagingLength: 10,
lengthChange: true,
autoWidth: true,
searching: true,
bInfo: true,
bSort : true,
});
</script>
</body>
</html>
Is there a more straightforward way of doing it ? Is it a good way to keep doing
list(infoDB.objects.value())
in a WHILE TRUE loop?

How to combine html, js and css from fiddle

I know the Question is silly and fiddle is only for testing your code,
but combining that into one code via putting JS under script<> and css under style<> is not working for me!
link to my code
I have used the following way as suggested by others:
<html>
<head>
<style type="text/css">
table tr td {
border: 1px solid;
padding: 4px;
}
<body>
<div ng-controller="MyCtrl">
<button ng-click="processData(allText)">
Display CSV as Data Table
</button>
<div id="divID">
<table style="border:1px solid">
<tr ng-repeat="x in data">
<td ng-repeat="y in x" rowspan="{{y.rows}}" colspan="{{y.cols}}">{{ y.data }}</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", function($scope) {
$scope.allText = "RS#2|Through Air CS#2|Over Surface CS#2|\nin.|mm|in.|mm|\nB |3/32\n (a)|2.4 \n (a)|3/32 \n (a)|2.4 \n (a)|\nD |1/16\n (a)|1.6 \n (a)|1/8 \n (a)|3.2 \n (a)|\n";
$scope.processData = function(allText) {
// split content based on new line
var allTextLines = allText.split(/\|\n|\r\n/);
var lines = [];
var r, c;
for (var i = 0; i < allTextLines.length; i++) {
// split content based on comma
var data = allTextLines[i].split('|');
var temp = [];
for (var j = 0; j < data.length; j++) {
if (data[j].indexOf("RS") !== -1) {
r = data[j].split("#").reverse()[0];
} else {
r = 0;
}
if (data[j].indexOf("CS") !== -1) {
c = data[j].split("#").reverse()[0];
} else {
c = 0;
}
temp.push({
"rows": r,
"cols": c,
"data": data[j].replace(/RS#.*$/, '').replace(/CS#.*$/, '')
});
}
lines.push(temp);
}
alert(JSON.stringify(lines));
$scope.data = lines;
}
});
The problem is that you are using an external JS framework, AngularJS. You will have to create another script tag which loads Angular as well. There are two ways you can do this: you can either download the angular source code and then load that into your HTML, or use a CDN.
To use the CDN, you can just add the following above your current <script> tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
Your final output should look like this:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<!-- some html elements -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
// more js here.
</script>
</body>

Create Javascript rows with user input

How would you start writing a for loop for the code provided below:
<html>
<head>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/><br/><br/>
<table border="1" id="theTable">
</table>
<script type="text/javascript">
function makeTable(){
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
</script>
</body>
</html>
As I suspect this is homework I will no provider a full code answer but instead provide you with a few guide lines that hopefully will help you.
You have the html and the javascript, in order to create new html elements you need to use the document.createElement(type) function that will create a new element, in your case - td/th ?
Then you need to insert it into your table
You do that by obtaining the table(by id/type) - search the web for this one its very simple.
And then using the append method on is with the created element.
You do all this process with a normal for loop that will run until the .value of the input tags you have in your html (Again, search for how to obtain these values)
Good luck =]
Is this what you are looking for?
function makeTable(){
// Get values of rows/cols inputs
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
// Check the values are in fact numbers
if (!isNaN(rows) && !isNaN(cols)) {
// Get the table element
var table = document.getElementById('theTable');
// Iterate through rows
for (var r = 0; r < rows; ++r) {
// Create row element
var tr = document.createElement('tr');
// Iterate through columns
for (var c = 0; c < cols; ++c) {
// Create cell element
var td = document.createElement('td');
// Setting some text content
td.textContent = 'R: ' + r + ', C: ' + c;
// Append cell to row
tr.appendChild(td);
}
// Append row to table
table.appendChild(tr);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
Cols: <input name="cols" id="cols" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/> <br/><br/>
<table border="1" id="theTable">
<script type="text/javascript">
function makeTable(){
var html = "";
var row=$('#rows').val();
var col=$('#cols').val();
for(var i=0; i<row; i++){
html+="<tr>";
for(var j=0;j<col; j++)
{
html+= '<td> Your data </td>';
}
html+="</tr>"
}
$('#theTable').html(html);
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
//create a dom element for the row to be added to the table
}
</script>
</body>
</html>
I have kept it simple. Hope it helps.

How to detect negative values in a <td> of table in html?

I have a table in html, I am using Tangle framework to make the values look dynamic of that table.
What I want is to place a check on a specific <td> if its numeric value ever gets negative, the entire <tr> of that particular <td> should change its background color to Red.
Can this be done using java script or some simple lines of code may solve this problem?
Please help me doing this.
<html>
<head>
<style type="text/css">
td.negative { color : red; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
function MakeNegative() {
TDs = document.getElementsByTagName('td');
for (var i=0; i<TDs.length; i++) {
var temp = TDs[i];
if (temp.firstChild.nodeValue.indexOf('-') == 0) temp.className = "negative";
}
}
//-->
</script>
</head>
<body>
<table id="mytable">
<caption>Some Financial Stuff</caption>
<thead>
<tr><th scope="col">Date</th><th scope="col">Money is good</th></tr>
</thead>
<tbody>
<tr><td>2006-05-01</td><td>19.95</td></tr>
<tr><td>2006-05-02</td><td>-54.54</td></tr>
<tr><td>2006-05-03</td><td>34.45</td></tr>
<tr><td>2006-05-04</td><td>88.00</td></tr>
<tr><td>2006-05-05</td><td>22.43</td></tr>
</tbody>
</table>
<script language="JavaScript" type="text/javascript">
<!--
MakeNegative();
//-->
</script>
</body>
I'd suggest:
var table = document.getElementsByTagName('table')[0],
cells = table.getElementsByTagName('td'),
hasNegative = 'hasNegative',
text = 'textContent' in document ? 'textContent' : 'innerText', num = 0;
for (var i = 0, len = cells.length; i < len; i++) {
num = parseFloat(cells[i][text]);
if (Math.abs(num) !== num) {
cells[i].parentNode.className += ' hasNegative';
}
}
JS Fiddle demo.
The rather bizarre means to determine negativity was a result of my previous, perhaps naive, check failing to differentiate between 0 and -0 (though I'm not quite sure whether negative-zero would pass, or fail, your criteria).

spit string and set them to map as a marker

i am try to create marker on map.
i am use bing Map
i have two string with comma separate.
in two different variable.
var Region = "Pune,Kolkata";
var Activity = "Cricket,One Day";
i am try this java-Script ajax:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/MapControl/mapcontrol.ashx?v=6.3c">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var Region = 'Pune,Kolkata';
var cntry_code= 'IN';
var Activity = "Cricket,One Day"
var map = null;
function GetMap() {
map = new VEMap('myMap');
map.LoadMap();
$(document).ready(function(){
var array_region = Region.split(',');
var array_activtiy= Activity.split(',');
for(var item_region in array_region)
for (var item_activity in array_activtiy)
{
$.ajax({
url: "http://services.gisgraphy.com//geocoding/geocode?address="+array_region[item_region]+"&country="+cntry_code+"&format=json",
async: false,
dataType:'jsonp',
success: function(data){
lat = data.result[0].lat;
lng = data.result[0].lng;
alert(lat);
alert(lng);
map.LoadMap(new VELatLong(lat,lng));
var pinpoint = map.GetCenter();
shape = new VEShape(VEShapeType.Pushpin, pinpoint);
shape.SetTitle("Activity Name:- ");
shape.SetDescription(array_activtiy[item_activity]+","+array_region[item_region]);
map.AddShape(shape);
}
});
alert(array_region[item_region]);
}
});
}
</script>
</head>
<body onload="GetMap();">
<div style="width:630px; background-color: #E0E0E0; height: 500px; border: 1px solid black">
<div id='myMap' style="position:relative; width:600px; height:400px; margin-left:15px"></div>
</div>
</body>
</html>
with this try to split string with comma.
and pass this to ajax url.
and got the lat and lng.
use this lat and lng.
set those place there Activity.
its work fine.
just little problem its add last place and last activity as a marker.
i think problem in my for loop.
please some one check it out my this query.
thanks.
You should not use the for(var item_region in array_region) construct with Arrays. Replace that line with something like:
for (var item_region, i = 0; i < array_region.length; i++)
item_region = array_region[i];
You will need to do a similar change on the following line - left as an exercise

Categories

Resources