I would like to import these data file values in an array.
so times[0] would be 23,8 etc...
Example data file web.txt (temperature values in C°):
23,8
23,2
22,8
22,0
... etc
The code below is what i have thusfar reading the web.txt
file and displaying the values in a browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p id="myid"></p>
<script>
var times = [];
$.get('web.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myid').append('<div>' + elem + '</div>');
});
});
</script>
</html>
That works.
Just rename
var lines = data.split("\n");
$.each(lines, function(n, elem) ...
to
times = data.split("\n");
$.each(times, function(n, elem) ...
Related
I'm not able to go through all children of an SVG file in JavaScript. I want to go through all the paths and perform a function on them(changing them to polygons).
I've tried creating an array of paths using querySelectorAll("path");, but it didn't work. Now I'm trying to sift through all the elements in the SVG file, converting paths as I go.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>
This gives me two errors:
XML Parsing Error: syntax error
Location: file:///C:/Users/Temp/Desktop/Experiment.html
Line Number 1, Column 1:.
ReferenceError: $ is not defined.
I've stopped trying to use doc.children() since it wasn't working.
Just add the jQuery library into your project.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
CODE:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Reader</title>
</head>
<body>
<input type="file" id="fileReader" />
<br>
<p id="Content"></p>
<script>
document.getElementById("fileReader").addEventListener('change',function(){
var fr = new FileReader();
fr.onload = function(){
console.log("File Loaded!")
}
parser = new DOMParser();
var doc = parser.parseFromString(fr.readAsText(this.files[0]), "text/xml");
console.log(doc);
var path = "path";
doc.querySelectorAll('*').forEach(function(){
if($(this).is(path)){
var polygon = doc.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute("id", $(this).getAttribute("id"));
console.log("Converting " + $(this).getAttribute("id"));
var len = $(this).getTotalLength();
var p = $(this).getPointAtLength(0);
var seg = $(this).getPathSegAtLength(0);
var stp=p.x+","+p.y;
for(var i=1; i<len; i++){
p=$(this).getPointAtLength(i);
if ($(this).getPathSegAtLength(i)>seg) {
stp=stp+" "+p.x+","+p.y;
seg = $(this).getPathSegAtLength(i);
}
}
polygon.setAttribute("points", stp);
$(this).replaceWith(polygon);
}
});
});
</script>
</body>
</html>
I'm getting the HTML code of a webpage using this parsing library called Kanna. Basically the stripped down version looks like this.
<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
window._sharedData = {
// Some JSON
};
</script>
<script type="text/javascript">
// Javascript code
</script>
<script type="text/javascript">
// More Javascript code
</script>
</body>
</html>
There are multiple script tags within the body. I want to access the one with the variable named window._sharedData and extract it's value which is a JSON dictionary.
I tried with using regular expressions but it's returning nil. Maybe something's wrong with my pattern?
if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {
let range = NSRange(location: 0, length: htmlText.utf8.count)
let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
let s = regex.firstMatch(in: htmlText, options: [], range: range)
print(s)
}
Or is there a better way to do this?
Here it is:
import Foundation
import Kanna
let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"
guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }
let body = doc.xpath("//script")
.compactMap { $0.text }
.filter { $0.contains("window._sharedData") }
.map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
.map { $0.dropLast(2) }
.first
print("body: ", body)
// body: Optional("{ \"string\": \"Hello World\" }")
After that you can check that body not nil and ready
I am working in excel import functionality in AngularJS. Now it's working fine by reading excel values. But I need read a particular column range row count
here I attached my tried code and expected output. Here I get row count as 7 but I need name and subject column row count only expected row count as 4 help how to solve this problem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular Js XLS</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.9.13/xlsx.full.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/angular-js-xlsx#0.0.3/angular-js-xlsx.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="myController">
<js-xls onread="read" onerror="error"></js-xls>
<!-- <input type="file" ng-change="read" onerror="error"> -->
</div>
</body>
<script type="text/javascript">
angular.module('MyApp', ['angular-js-xlsx'])
.controller('myController', function($scope) {
$scope.read = function (workbook) {
debugger;
var headerNames = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]], { header: 1 })[0];
var data = XLSX.utils.sheet_to_json( workbook.Sheets[workbook.SheetNames[0]]);
console.log(headerNames);
console.log(data);
for (var row in data)
{
Object.keys(data[row]).forEach(function(key) {
console.log("Key = >" + key);
console.log("Value => " + data[row][key]);
console.log("===========================");
});
}
}
$scope.error = function (e) {
console.log(e);
}
});
</script>
</html>
Data
I have the code below that returns the rowIndex of the clicked row.
The table uses the info from the WebViewString element, it has an csv formatted data and always have at least one column.
I need to get the value of the first column of that row. How to???
I know nothing about JS... just need this little modification but couldn't find anything by myself.
<!doctype html>
<head>
<meta name="author" content="puravidaapps.com">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="materialize.min.css" media="screen,projection"/>
<title>Table Layout</title>
</head>
<body>
<div id="myTable"></div>
<script>
// if you have commas inside your text, feel free to use another delimiter, for example |
var delimiter = ",";
// get the table to display from the window.AppInventor object and split at new line
var urlArray = window.AppInventor.getWebViewString().split("\n");
//var urlArray = location.search.slice(1).split("/n");
var doc = document;
var fragment = doc.createDocumentFragment();
var thead = doc.createElement("thead");
var tr = doc.createElement("tr");
// split at delimiter
var rowArray = urlArray[0].split(delimiter);
addRow(thead, "th");
fragment.appendChild(thead);
var tbody = doc.createElement("tbody");
for(i=1;i<urlArray.length;i++){
var tr = doc.createElement("tr");
// split at delimiter
var rowArray = urlArray[i].split(delimiter);
tr.addEventListener ("click", function () {
// return index (add 1 because first row is the header row)
// window.document.title = this.rowIndex + 1;
window.AppInventor.setWebViewString(this.rowIndex + 1);
});
addRow(tbody, "td");
}
fragment.appendChild(tbody);
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("myTable").appendChild(table);
// http://stackoverflow.com/a/9236195/1545993
doc.getElementById("myTable").getElementsByTagName('table')[0].className = "striped";
function addRow(dom, tag) {
for(j=0;j<rowArray.length;j++){
var el = doc.createElement(tag);
el.innerHTML = rowArray[j];
tr.appendChild(el);
dom.appendChild(tr);
}
}
</script>
</body>
</html>
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>