I want to display specific fields from an external CSV file on a web site with using JavaScript.
I tried to parse that file with using "Papa parse" like this:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Parse remote CSV to HTML Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script src='https://code.jquery.com/jquery-2.1.4.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.0/mustache.min.js'></script>
<script>
Papa.parse("https://dl.dropboxusercontent.com/s/....../data.csv?dl=0", {
download: true,
header: true,
complete: function(results) {
console.log(results);
}
});
</script>
</body>
</html>
And this give me the result in console:
console.log
My question is;
How can I display a specific data from this data set in a web site like:
Battery Level: 0.62
Altimeter Pressure: 99.44185
Horizontal Accuracy: 65
etc. etc.
Taking Battery Level as an example (the other fields are similar and you should be able to figure it out youself):
var data = results.data
var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'your_div_id_'+i.toString());
newdiv.innerHTML = 'Battery Level: '+data[i].batteryLevel.toString();
}
Related
I'm using Visual Studio to practice javascript. When I save it and click Go Live to open it in a browser, nothing shows up after I select the file. Even though I saved it in a folder with and index file.
Heres the javascript file:
const penholder = {
name: "Bamboo Blessing pen holder",
penVolume: 10,
colour: "bamboo",
heightInches: 6,
diameterInches: 3,
currentPenCount: 2,
penClickStatus: {
whitePen: true,
transparentPen: false,
},
clickPen: function (whiteClickStatus, transparentClickStatus) {
this.penClickStatus.whitePen = whiteClickStatus;
this.penClickStatus.transparentPen = transparentClickStatus;
},
};
console.log("The backpack object: ", penholder);
and here's the index file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Module demo</title>
<script src="bambooPenHolder.js"></script>
</head>
<body></body>
</html>
Can anyone explain what I'm doing wrong? And if you have any suggestions for how I should format my posts here, please let me know. I'm new here.
I have an array of object. I'd like to be able to display in the HTML the object "name" property just by invoking a function from the external js file. Any help?
let cakes = [{
name: "Savarina",
flavour: "frisca"
},
{
name: "Briosa",
flavour: "ciocolata"
}];
function renderProducts() {
cakes.forEach( function(element) {
document.body.innerHTML = `<p> ${element.name} </p>`;
});
}
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="Stylesheets/styles.css">
</head>
<body>
<script> renderProducts();</script>
<script> src="Scripts/script.js"</script>
</body>
</html>
You need to specify where you want to output the information, and append it rather than just set the document html which will obviously overwrite everything.
Create an output container, like this...
let cakes = [{
name: "Savarina",
flavour: "frisca"
},
{
name: "Briosa",
flavour: "ciocolata"
}];
function renderProducts() {
var output = document.querySelector("#output-div");
cakes.forEach( function(element) {
output.innerHTML += `<p> ${element.name} </p>`;
});
}
// only run the render function when the page has loaded,
// so we know the div exists.
window.addEventListener("load", renderProducts);
<div id="output-div"></div>
I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG
I'm trying to load two scripts that were functionally deferred on account of their type attributes being non-standard i.e. text/javascript/defer. Doing this causes the parser to ignore them so I want to reload them using JavaScript.
My HTML is as below:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>
$(document).ready(function(){
var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;
if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {
var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});
//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}
});
</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>
jquery.js is version 1.11.2. test3.js and test4.js reference the javascript files I want to load, and they contain console.log('test3.js is loaded'); and console.log('test4.js is loaded'); respectively.
The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the console.log message when I load the script.
How can I fix this?
It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.
$(document).ready(function(){
console.log("main");
var $body = $($("body")[0]);
var $scripts = $("[type='text/javascript/defer']");
$scripts.each(function(){
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", $(this).attr("src"));
$body.append(scriptTag);
});
});
Try to append your script at the end of body, so instead do:
document.getElementsByTagName("body")[0].appendChild(fileref);
I have written a code which extracts a specific table from a webpage. The website is dynamic and it updates the values in the table once every half an hour. My Javascript for parsing the website does reload the website once every 30 minutes. But the data extracted as JSON are only data of the particular time. But, I want to append or concatenate all the data every time the site reloads(i.e., i need the present list of data concatenated with previous list, as long as the program is running) How do i do that?.
The webpage is: https://www.emcsg.com/marketdata/priceinformation
The table required is: View 72 periods
My code is as follows:
<html>
<head>
<title>Pricing </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<meta http-equiv="refresh" content="1800" /><!--Reloads page every 30 minutes-->
<script>
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
function someFunction(results){
var html = $(results);
var table = html.find(".view72PeriodsWrapper");
$('#loadedContent').css("display","").html(table);
}
</script>
</head>
<body>
<br><br>
<div id="result"></div>
<div id="loadedContent"></div>
</body>
</html>