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>";
Related
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])
}
I have JSON data and I guess my JSON is works but there is something that I didn't understand how it's going to work ? when I wrote cities or countries nothing happend how will I make it work ?
I havedata-list attribute and when I clicked my input my data-list opening automatically it's ok so far.but if I wrote something my inline data-list attribute musn't work anymore only my Json must work how can I do that ?
I'm using Awesomplete plugin and if you want to see my project on codepen please click to see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = "Cities : " + myObj.cities;
document.getElementById("demo1").innerHTML = "countries : " + myObj.countries;
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
} else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
} else {
comboplete.close();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet" />
<div id="demo"></div>
<div id="demo1"></div>
<!--<input type="text" class="awesomplete" data-list="PHP,ASP,ASP.NET,Python,CSS,HTML,C#,C++,Delphi,Visual Basic" onclick="showlist()">-->
<br><br> with auto list
<input id="test" data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" class="dropdown-input" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
You have to access the attribute "data-list" of your input and set your json as data source.
Try this:
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)
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>
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>
I have a java class which returns a JSON object and I need to pass this JSON object to gojs javascript, here is the sample of my gojs javascript file(gojs_org_view.js)
function init() {
var g = go.GraphObject.make; // for conciseness in defining templates
myDiagram = new go.Diagram("myDiagram"); // must be the ID or reference to div
var graygrad = g(go.Brush, go.Brush.Linear, { 0: "rgb(125, 125, 125)", 1: "rgb(86, 86, 86)", 1: "rgb(86, 86, 86)" });
var unassocArray =[{"id":"12" , "name":"Bugs Bunny", "title":"Head Bunny"},
{"id":"13" , "name":"Honey Bunny", "title":"Wife Bunny"},
{"id":"14" , "name":"Lola Bunny", "title":"Lil' Bunny"},
{"id":"15" , "name":"Mickey Mouse", "title":"Looney In Charge"}];
//some javascript code...........
function save() {
var json = JSON.parse(myDiagram.model.toJson());
document.getElementById("mySavedModel").value = JSON.stringify(json.nodeDataArray, null, ' ');
}
function load() {
var nodeDataArray =
[ {"id":"1", "pid":"1", "name":"Corrado 'Junior' Soprano", "title":"The Boss", "email":"boss#sopranos.net"},
{"id":"2", "pid":"1", "name":"Tony Soprano", "title":"Underboss", "email":"underboss#sopranos.net"},
{"id":"3", "pid":"1", "name":"Herman 'Hesh' Rabkin", "title":"Advisor", "email":"hesh#sopranos.net"},
{"id":"4", "pid":"2", "name":"Paulie Walnuts", "title":"Capo", "email":"paulie#sopranos.net"},
{"id":"5", "pid":"2", "name":"Ralph Cifaretto", "title":"Capo MIA", "email":"ralph#sopranos.net"},
{"id":"6", "pid":"2", "name":"Silvio Dante", "title":"Consigliere", "email":"silvio#sopranos.net"}];
var model = new go.TreeModel();
model.nodeKeyProperty = "id";
model.nodeParentKeyProperty = "pid";
model.nodeDataArray = nodeDataArray;
myDiagram.model = model;
myDiagram.undoManager.isEnabled = true;
}
function onSelectionChanged(e) {
var node = e.diagram.selection.first();
if (node instanceof go.Node) {
updateProperties(node.data);
} else {
updateProperties(null);
}
}
// Update the HTML elements for editing the properties of the currently selected node, if any
function updateProperties(data) {
if (data === null) {
jQuery("#selected").css('visibility', 'hidden');
jQuery("#name").html("");
jQuery("#title").html("");
jQuery("#email").html("");
jQuery("#site").html("");
jQuery("#superior").html("");
} else {
jQuery("#selected").css('display', 'block');
jQuery("#name").html("ID: " + data.id + " Name: " + data.fullname || "");
jQuery("#title").html("Title: " + data.title || "");
jQuery("#email").html("Email: " + data.email || "");
jQuery("#site").html("Site: " + data.siteName || "");
jQuery("#superior").html("Superior: " + data.pname || "");
}
}
The javascript variables unassocArray and nodeDataArray are hard-coded instead these values have to come from java class or xhtml(I am not sure which is the best method to send JSON object to gojs javascript file since am new to prime faces and JSON).
Here is the xhtml code calling gojs
<p:panel id="relationshipsPanel">
<h:outputScript library="js" name="go.js" />
<h:outputScript library="js" name="gojs_org_view.js" />
<h:outputStylesheet library="css" name="gojs_org_view.css"/>
<div id="sample">
<div id="myPalette" class="myPaletteClass"></div>
<div id="myDiagram" class="myDiagramClass"></div>
<div id="myOverview" class="inner"></div>
<div id="selected" class="selectedClass"></div>
</div>
</p:panel>
I tried the hidden value as below, I added following line in my view
In gojs_org_view.js i did
window.console.log("RANA ORG JSON--------------------->"+document.getElementById("relationshipsForm:arrVal").value);
var nodeDataArray = JSON.parse(document.getElementById("relationshipsForm:arrVal").value);
In the console am getting the following JSON object from view to the javascript but its throwing error "Uncaught SyntaxError: Unexpected token i" at var nodeDataArray = JSON.parse(document.getElementById("relationshipsForm:arrVal").value);
You can request data from server using an AJAX call and get the data. if that is not an option then you can put the data in a hidden field on the page and then access it in your load() function, like you are doing it in your save() function using document.getElementById.