How to combine html, js and css from fiddle - javascript

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>

Related

Dynamic creation of google charts in single page

I'm attempting to dynamically create multiple charts in a single html page, everything loads perfectly, except that the graph that is displayed last is the only one that has interactivity available (ex: hover over points to read data, click on legend to highlight line..) while the others will only display static charts.
HTML Code:
<html>
<head>
<title>Dashboard</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type = "text/javascript" src = "./scripts/scripts.js"> </script>
</head>
<body>
</body>
<script language = "JavaScript">
var dashboard = getParameterByName("dashboard");
google.charts.load('current', {packages: ['corechart','line']});
buildDashboard(dashboard);
</script>
</html>
Main JS functions:
function buildDashboard(dashboard)
{
var panels = getPanels(dashboard);
google.charts.setOnLoadCallback(function(){
drawCharts(dashboard, panels);
});
}
function drawCharts(dashboard, panels)
{
for(var i = 0; i < panels.length; i++)
{
var panel = panels[i];
var _data = getPanelData(dashboard, panel.Id);
if(panel["Type"] == "LineChart")
{
var legend = JSON.parse(JSON.stringify(_data[0]));
var options = buildLineChartOptions(panel, legend);
var data = google.visualization.arrayToDataTable(beautifyData(panel, _data));
var divname = panel.Id;
if(!document.getElementById(divname))
document.body.innerHTML += "<div id = " + divname + " style = \"width: 100%; height: 600px; margin: 0 auto\"></div>";
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(data, options);
}
}
}
Solved: The problem was solved by creating the <div> elements for all charts prior to drawing the charts one by one.

How do I include jQuery in my js file without html

I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");

Pass variable in Google Apps Scriptlet to 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>

${variable} in javascript not substituted in jsp

I am trying to add direction to a line overlay i have added to map using openlayers. I have created map and line overlay inside my jsp but the problem is that when ${variable} is used in html file, I am getting output as expected with correct direction shown. But when implemented inside jsp all arrows seem to b pointing to just one direction.
I think the problem is that ${variable} in javascript not substituted in jsp.
Here is the piece of code.
direction.jsp
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Line Direction Arrow in OpenLayers</title>
<link rel="stylesheet" href="http://openlayers.org/dev/theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="../theme/default/style.css" type="text/css">
<link rel="stylesheet" href="style.css" type="text/css">
<style type="text/css">
#map {
width: 600px;
height: 400px;
border: 1px solid #ccc;
}
</style>
<script src="js-libraries/OpenLayers.js" type="text/javascript"></script>
<script src="js-libraries/directions.js" type="text/javascript"></script>
<script type="text/javascript">
var map = null;
var myNetwork =null;
function init(){
map = new OpenLayers.Map('map');
var ol_osm = new OpenLayers.Layer.OSM("Simple OSM Map");
map.addLayers([ol_osm]);
//vector layer
var layer = new OpenLayers.Layer.Vector("Line");
map.addLayer(layer);
// add edit panel
var editPanel = new OpenLayers.Control.EditingToolbar(layer);
map.addControl(editPanel);
//add direction layer
OpenLayers.Renderer.symbol.arrow = [0,2, 1,0, 2,2, 1,0, 0,2];
var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
{graphicName:"arrow",rotation : "${angle}"},
OpenLayers.Feature.Vector.style["default"]));
var dirLayer = new OpenLayers.Layer.Vector("direction", {styleMap: styleMap});
map.addLayer(dirLayer);
map.setCenter(new OpenLayers.LonLat(-702335,7043201),15);
//console.log("Starting map");
}
function updateDirection() {
//alert(map.layers[2].name);
map.layers[2].removeAllFeatures();
var points=[];
var features =map.layers[1].features;
//alert(features.length);
for (var i=0;i<features.length ;i++ ) {
var linePoints = createDirection(features[i].geometry,get_position_value(),get_foreachseg_value()) ;
//alert(get_foreachseg_value());
// for (var j=0;j<linePoints.length ;j++ ) {
// linePoints[j].attributes.lineFid = features[i].fid;
// }
points =points.concat(linePoints);
// alert(points);
}
map.layers[2].addFeatures(points);
}
function get_position_value() {
for (var i=0; i < document.direction.position.length; i++)
{
if (document.direction.position[i].checked)
{
return document.direction.position[i].value;
}
}
}
function get_foreachseg_value() {
if (document.direction.foreachseg.checked){
return true;
} else {
return false;
}
}
</script>
</head>
<body onload="init()">
<table><tr>
<td><div id="map" class="smallmap"></div></td>
<td><div align="left">
<form name="direction">
<input type="radio" name="position" value="start"/> start <br>
<input type="radio" name="position" value="end"/> end <br>
<input type="radio" name="position" value="middle" CHECKED/>middle <br>
<input type="checkbox" name="foreachseg" /> Create for each segment of line <br>
<input type=button value="Update" onClick=updateDirection(); />
</form>
</div></td>
</tr></table>
</body>
</html>
Is there anyway to get the corresponding angle in jsp? the page seems to b working fine when the file was renamed direction.html But when renamed as direction.jsp the angle value is not received correctly. I need to use this with my jsp application. please help.
Thanks and Regards
Ginger.
As JSP is server side and javascript is client side so you can't pass parameters like this, an alternate would be to add angle as hidden field in your jsp
<input type="hidden" value="angle_value_comes_here" id="angle"/>
and then access it in javascript using
var angle = $('#angle').val();
Hope it helps
I am posting my updated code in here.
function updateDirection() {
flagMarkerStatus = 5;
var angles = 0;
dirLayer.removeAllFeatures();
var linePoints=[];
var points=[];
var features =lineLayer.features;
document.getElementById("angle").value="";
for (var i=0;i<features.length ;i++ ) {
var linePoints = createDirection(features[i].geometry,"middle",true);
points =points.concat(linePoints);
angles = document.getElementById("angle").value;
//'angle' div contains angle values seperated by '~'
angles=angles.replace(/\[|\]/g, '');
angles=angles.split("~");
for(var i=0;i<linePoints.length;i++){
var styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
{graphicName:"arrow",rotation : angles[i],strokeWidth: 3,strokeColor: "#ff0000"},
OpenLayers.Feature.Vector.style["default"]));
dirLayer.styleMap = styleMap;
dirLayer.addFeatures(linePoints[i]);
}
}
}

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).

Categories

Resources