Displaying object properties from an array by DOM manipulation - javascript

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>

Related

Javascript file not showing up on browser

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.

Array methods inside HTML

I'm trying to make a very simple html document with some vanilla JavaScript to sort some elements in it.
I've been able to use .map() to print all the elements of an array, but I'd like to include them in html elements. For example. using an <h1> or a <p>.
This is the code I have so far:
<!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>Test</title>
</head>
<body onload="mapping()">
<h1>
<script>
const array = [1, 2, 3];
function mapping() {
array.map(arrayItem => {
document.write(arrayItem)
})
}
</script>
</h1>
</body>
</html>
How can I include HTML inside the script, so I can do something with each one of those returned elements? I mean, something like this:
<script>
const array = [1, 2, 3];
function mapping() {
array.map(arrayItem => {
<h1>document.write(arrayItem)</h1>
})
}
</script>
This should work.
<!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>Test</title>
</head>
<body onload="mapping()">
<script>
const array = [1, 2, 3];
function mapping() {
array.forEach(arrayItem => {
var newEle = document.createElement('h1');
newEle.innerHTML = arrayItem;
document.body.appendChild(newEle);
});
}
</script>
</body>
</html>
I guess what you want to do is something like this:
<div>
<script type="text/javascript">
document.write("<h1>Main title</h1>")
</script>
</div>
You might want to consider checking the documentation for Javascript at the link I provided. It gives a lot of useful examples and methods. I took the snippet code from there.Hope it helps.

Function is not define

Here is my code :
// And my javascript file verbatims.js :
class Verbatims {
list() {
return ["c'est super", "j'aime pas", "ça marche bien"];
}
}
module.exports = Verbatims;
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta content="X-Content-Type-Options: nosniff">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>
<script src="/src/verbatims.js" type="application/javascript"></script>
<title>My Project</title>
</head>
<body>
<div id="PRISME_data">
Le nombre de requête est de : {{ nb_request }}<br>
<button v-on:click="change">Change value</button>
<button v-on:click="stop">Arrêter</button>
</div>
<script>
let app = new Vue({
el:'#PRISME_data',
data: {
nb_request: "toto",
ite: 0
},
methods: {
change: function() {
changeNbRequest()
},
stop: function() {
clearInterval()
}
}
});
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
</body>
</html>
When I try to display my page with my node server I have this error :
Uncaught ReferenceError: Verbatims is not defined at index:45
on this line : let verbatim = new Verbatims().list()[ite];
I don't see why, I have try a lot of things but nothing work ! Do you have any idea ?
Thank you :)
This might be happening because of the following:
The verbatims.js file is not loading in the browser because of
wrong path.
The verbatims.js file that reached the browser does
not contain your class.
You did not import the Verbatims class on the referencing script.
Fix for 3rd option should be like this:
<script type="module">
import {Verbatims} from './src/vebatim.js';
....ommitted for brevity
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
Additional TIP
To improve your code, try to place all the JS code inside your index.html to an external file so you can take advantage of ES6 import/export features.

how to pass array to inner html in polymer

I am totally new to polymer.I want to draw a graph...
I have one html where I include attributes like this... for the dom module
<some-container content_content-type = 'Real Estate' content_content-num = 'PF HP 001078' key-type = 'vpn_key' graphmax = 620000 graphmin = 540000 currency = 'USD' oldvalue-amount = 550000 new-value-amount = 2300 new-valuecolor = 'green-text' new-valueplusminus = '+' morelink = '#' containerlink = 'education.html' graphdata = [['Tue', 600000],['Wed', 590000],['Thu', 580000],['Fri', 575000],['Sat', 590000],['Sun', 575000],['Mon', 550000],['Tue', null]]></some-container>
Now I want to send this array graphdata as parameter… as I sent the others like… content_content-type, content_content-num, etc.
<dom-module id="some-container">
<template>
….HTML…
</template>
<script>
Polymer({
is: 'some-container',
properties: {
content_contentType: {
type: String,
notify: true
},
content_contentNum: {
type: String,
notify: true
},
….
graphdata: {
type: Array,
value: []
},
….
};
attached: function() {
this._drawgraph(this.graphmax,this.graphmin,this.graphid,this.graphdata); // _drawgraph is some other function where functionality/calculations are…
//If I debug I see this.graphmax, this.graphmin has data… but not this.graphdata
},
But I see that this.graphdata is not getting data. Its undefined.
Any suggestion how do I pass the array from the external HTML
To pass quoted [JSON|Array] to element property directly in HTML you must invert the quotes. The attribute value must be surrounded by single quotes and the actual string must use double quotes. Otherwise Polymer fails to parse it, because single quotes are not correct JSON syntax. Thus your code should be
<some-container graphdata='[["Tue", 600000],["Wed", 590000],["Thu", 580000],["Fri", 575000],["Sat", 590000],["Sun", 575000],["Mon", 550000],["Tue", null]]'></some-container>
It would seem that the way it is parsed it is treated as JSON by Polymer, so you have to always use single quotes for array attributes, and double quotes inside the array.
Here's a working example, it seems a little slow to run on StackOverflow, but it should work after some few seconds.
<!doctype html>
<html>
<head>
<title>Testing App</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="http://polygit.org/polymer+:master/components/polymer/polymer.html">
</head>
<body>
<dom-module id="example-element">
<template>
<template is="dom-repeat" items="[[_processArray(graphdata)]]">
<p>[[item.key]]: [[item.value]]</p>
</template>
</template>
<script>
Polymer({
is: 'example-element',
properties: {
graphdata: {
type: Array
}
},
_processArray(arr) {
var processed = [];
for (var i = 0; i < arr.length; i++) {
processed.push({
key: arr[i][0],
value: arr[i][1]
});
}
return processed;
}
});
</script>
</dom-module>
<example-element graphdata='[["Tue", 600000],["Wed", 590000],["Thu", 580000],["Fri", 575000],["Sat", 590000],["Sun", 575000],["Mon", 550000],["Tue", null]]'></example-element>
</body>
</html>

Displaying specific data from a CSV/JSON file

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();
}

Categories

Resources