appendChild usage, variable array Javascript - javascript

trying to use appendChild to create a child element in a paragraph, I think I'm missing something fundamental here but I can't figure out what and not sure I'm using appendChild correctly.
<!DOCTYPE html>
<html>
<body>
<p>Accessing Variables from an Array</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
childtest=document.getElementById("demo").innerHTML=employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>
What I'm trying to do is create a child of "demo" and take the second array of employees and make that the child element and output that underneath the first output.

childtest is not a element here.
// Create a new empty <p> element.
var childtest = document.createElement('p');
// Set the innerHTML.
childtest.innerHTML = employees[1].firstname;
// Append that <p> element.
first.appendChild(childtest);

your problem is that you're not creating a new element and with .innerHTML you're just overwriting existing
fiddle
var employees = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}];
document.getElementById("demo").innerHTML = employees[0].firstName + " " + employees[0].lastName;
var newEl = document.createTextNode(employees[1].firstName);
first = document.getElementById("demo");
first.appendChild(newEl);

Katpoes got it right, just for clarification, this works:
<!DOCTYPE html>
<html>
<body>
<p>How to create a JavaScript object array.</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
var childtest=document.createElement("p");
childtest.innerHTML = employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>

Related

How to get value of variable from HTML text in Google Applicatioin Script?

I get valid HTML code using UrlFetchApp.fetch(url,options). The part I am interested in looks like
<script type="text/javascript">
var map = am4core.create("mapdiv", am4maps.MapChart);
map.geodata = am4geodata_worldLow;
map.projection = new am4maps.projections.Miller();
var polygonSeries = new am4maps.MapPolygonSeries();
polygonSeries.useGeodata = true;
map.series.push(polygonSeries);
// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonSeries.data = [{
"id": "AF",
"value0": "2",
"value3": 3.2,
"fill": am4core.color("#0C6175")
}, {
"id": "AL",
"value0": "2",
"value3": 2.5,
"fill": am4core.color("#0C6175")
}, {
"id": "DZ",
"name": "Algeria",
"value0": "1",
"value3": 3.2,
"fill": am4core.color("#68C2C3")
}];
polygonTemplate.propertyFields.fill = "fill";
</script>
Could you suggest how to get the value of polygonSeries.data javascript variable assigned to GAS variable? I cannot think of anything besides parsing the HTML line by line, find polygonSeries.data and then parse till I get }]; I do not think it is the best way though.
Suggestion
You can use this sample regex method script & adjust it based on your needs:
Script:
function getData() {
var htmlcontent = HtmlService.createHtmlOutputFromFile('Index').getContent(); //Sample line to get the content of the Html file
var clean = htmlcontent.replace(/ /g,''); //Clean the code by removing multiple spaces
var regExp = new RegExp("polygonSeries.data=(.*)polygonTemplate", "s");
var data = regExp.exec(clean)[1];
var arr = data.split(/\r?\n/) //split all data by new lines
var newArr = []; //container of all the values
arr.forEach(res => { //Sample lines of code to clean each values to be placed later as array values
if(res.length > 3){
try{
var temp = res.replace(",","").split(":");
newArr.push([temp[0].replace(/"/gm, ''),temp[1].replace(/"/gm, '')])
}catch{
var temp = res.split(":");
newArr.push([temp[0].replace(/"/gm, ''),temp[1].replace(/"/gm, '')])
}
}
});
Logger.log(newArr);
}
Sample Index.html file:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Your Title Here</TITLE>
<script type="text/javascript">
var map = am4core.create("mapdiv", am4maps.MapChart);
map.geodata = am4geodata_worldLow;
map.projection = new am4maps.projections.Miller();
var polygonSeries = new am4maps.MapPolygonSeries();
polygonSeries.useGeodata = true;
map.series.push(polygonSeries);
// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonSeries.data = [{
"id": "AF",
"value0": "2",
"value3": 3.2,
"fill": am4core.color("#0C6175")
}, {
"id": "AL",
"value0": "2",
"value3": 2.5,
"fill": am4core.color("#0C6175")
}, {
"id": "DZ",
"name": "Algeria",
"value0": "1",
"value3": 3.2,
"fill": am4core.color("#68C2C3")
}];
polygonTemplate.propertyFields.fill = "fill";
</script>
</HEAD>
<BODY BGCOLOR="FFFFFF">
<CENTER><IMG SRC="clouds.jpg" ALIGN="BOTTOM"> </CENTER>
<HR>
Link Name
is a link to another nifty site
<H1>This is a Header</H1>
<H2>This is a Medium Header</H2>
Send me mail at <a href="mailto:support#yourcompany.com">
support#yourcompany.com</a>.
<P> This is a new paragraph!
<P> <B>This is a new paragraph!</B>
<BR> <B><I>This is a new sentence without a paragraph break, in bold italics.</I></B>
<HR>
</BODY>
</HTML>
Sample Result:
Based on Irvin's code I implemented this one. I was originally looking for simple solution where I would not have to use any kind of cycle - for nor each or so.
function getData(){
var html = getZZStat()
var clean = html.replace(/=/g,'') // remove = otherwise eval() would not work
var endString = "}]"
var regExp = new RegExp("polygonSeries.data(.*)"+endString, "s");
var data = regExp.exec(clean)[1]+endString
var tmp = data.replace(/\)/g,'').replace(/am4core.color\(/g,'') // remove variable "am4core" so eval() works
var finalData = eval(tmp)
console.log("finalData ",finalData.length)
console.log(finalData[0])
console.log(finalData[finalData.length-1])
console.log(finalData[finalData.length-2])
}

Print new Prompt

I am trying to print in the document the new JavaScript object that the user has created by a button and a prompt. What I want is to print it under the last one created but it just overwrites the last object prompted.
var actividades = {
"Colores" : [
{"color": "Rojo"},
{"color": "Verde"},
{"color": "Azul" }
],
"Deportes": [
{"jugador":"messi", "edad": "30"},
{"jugador":"lebron", "edad": "20"}
]
}
function crear(){
var categoria = prompt("Seleccione un color");
actividades.Colores.push({"color": categoria});
JSON.stringify(categoria);
document.getElementById("colores").innerHTML += categoria + "<br>";
console.log(actividades.Colores);
}
<button onclick="crear()">Crear Json</button>
<div id="colores">
</div>
<div id="deportes">
</div>
You need to store output of JSON.stringify(categoria); in a variable
var colors = JSON.stringify(actividades.Colores);
document.getElementById("colores").innerHTML += colors + "<br>";

Join array elements from second onward

I am building a csv, I need to skip the metadata from the array which is at 1st pos
How do I get a output like
"2","3","4"
"6","7","8"
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var list = [
["meta1", "2", "3", "4"],
["meta2", "6", "7", "8"]
];
var csv = list.map(function(d) {
return '"' + d.join('","') + '"';
}).join('<br/>');
var x = document.getElementById("demo");
x.innerHTML = csv;
}
</script>
</body>
</html>
You can call shift() which remove first element from array
https://www.w3schools.com/jsref/jsref_shift.asp
Or
you can use splice().Usage is explained for example here:
How to remove element from an array in JavaScript?

Get data from JSON based upon the input received

I need to fetch data based upon the input received.
For example, if the input is 'Royal python', I should get details of Royal python.but with the following code, i get error saying 'The file you asked for does not exist'. But I get the value into fname. But not sure if the function is correct to fetch data from from array.Also I wanted to know if there is any shorter way to do this. Please help?
I'm using JavaScript for this, my code and the web page look are below:
<!DOCTYPE html>
<html>
<body>
<form> <input type="text" name="fname" required>
<button onclick="myFunction()">OK</button> `enter code here`
</form>
<p id="demo"></p>
<script> var text = '{"animals":[' +
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' +
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri",` "Zoo":"Welsh Mountain Zoo","Number":35 },' +`
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes", "Zoo":"Blackpool Zoo","Number":8 }]}';
obj = JSON.parse(text);
//function to fetch data based on input
function myFunction(fname)
{ var ani = "";
if (document.getElementByname("fname")="Royal Python")
var ani = document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }} </body> </html>
Here is a solution to your problem that uses a for loop to check each index of the animal array for a match. This match will be case-insensitive also.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<input type="text" name="fname" required>
<button onclick="fetchAnimal()">OK</button> `enter code here`
<script>
var animalsArr = [{
"commonName": "Royal Python",
"order": "Squamata",
"family": "Boidae",
"genus": "Python",
"species": "regius",
"zoo": "Blackpool Zoo",
"number": 4
}, {
"commonName": "Emperor Penguin",
"order": "Sphenisciformes",
"family": "Spheniscidae",
"genus": "Aptenodytes",
"species": "forsteri",
"zoo": "Welsh Mountain Zoo",
"number": 35
}, {
"commonName": "Chimpanzee",
"order": "Primates",
"family": "Pongidae",
"genus": "Pan",
"species": "troglodytes",
"zoo": "Blackpool Zoo",
"number": 8
}]
function fetchAnimal() {
var i;
var len = animalsArr.length;
// convert input name to lower-case
var name = document.getElementsByName('fname')[0].value.toLowerCase();
for (i = 0; i < len; i++) {
// check to see if lower-case input is the same as lower-case animal name (this ensures the match is case-insensitive)
if (animalsArr[i].commonName.toLowerCase() === name) {
document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
}
}
}
</script>
</body>
</html>
Note: It is highly recommended move the JS code into an external script file if you intend to add more interactivity to the page.
There are a number of issues in your code:
document.getElementByname("fname")="Royal Python" should be document.getElementsByName("fname")[0].value == "Royal Python"
Also, it's cumbersome to write the text string and then parse it as JSON. Just use a JavaScript object.
You're also making it difficult on yourself when trying to determine the animal. Use Array.findIndex() if your browser supports it.
Here's a working example:
var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35 }, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes", Zoo:"Blackpool Zoo",Number:8 }]};
//function to fetch data based on input
function myFunction() {
var name = document.getElementsByName("fname")[0].value;
var index = obj.animals.findIndex(function(item) {
return item.CommonName === name;
});
if (index >= 0) {
document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
}
}
<input type="text" name="fname" required value="Royal Python">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>

Create Repeatable HTML Form and Load Info from a JS Array

I have a JS array with info in it. I want to populate some sort of repeatable object such that I can display all the info in the same way (formatted). I assumed I would need to use a HTML form, but now can't figure out how to exactly populate it with the information from my JS array. I want to make this happen on a page load, but for right now I am trying to test it with a button.
<html>
<head>
</head>
<body>
<script>
var myArray = [
{
"title" : "My First Place",
"address": "My First Address",
},
{
"title" : "Treehouse",
"address": "off in the woods",
},
{
"title" : "My New Place",
"address": "Home Sweet Home",
}
];
function addRow() {
var itm = document.getElementById("infoArea");
var cln = itm.cloneNode(true);
for(var i = 0; i < myArray.length; i++){
document.getElementById("repeatafterme").appendChild(cln);
}
}
</script>
<div id="repeatafterme"></div>
<form name="myform" id="infoArea">
<fieldset>
<legend><label id="myFormID"><output name="title"></output><label></legend>
<label><output name="address"></output></label>
</fieldset>
</form>
<INPUT TYPE="button" NAME="myButton" VALUE="Press This" onclick="addRow()">
</body>
</html>
itm.cloneNode(true) must be within the block for and set different id to element new.
To set value of array title and address should access to children for get elements out
function addRow() {
var itm = document.getElementById("infoArea");
for(var i = 0; i < myArray.length; i++){
var cln = itm.cloneNode(true);
cln.id = "id" + i;
var outTitle = cln.childNodes[1].childNodes[1].childNodes[0].childNodes[0];
outTitle.value = myArray[i].title;
var outAddress = cln.childNodes[1].childNodes[3].childNodes[0];
outAddress.value = myArray[i].address;
document.getElementById("repeatafterme").appendChild(cln);
}
}
result: https://jsfiddle.net/cmedina/sL0v07tt/1/

Categories