how to pass array to inner html in polymer - javascript

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>

Related

Displaying object properties from an array by DOM manipulation

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>

How to get first element displayed in dom-repeat?

I want to show first element of dom-repeat as display on form. And other should be added by clicking on button. How this scenario could be possible in polymer. As shown in image.
As shown in above image room#1 should be display by default and from room#2 should be added on click of button.
code-
<form is="iron-form" id="form" method="post" action="/form/handler">
<template is='dom-repeat' items='{{ rooms }}'>
<div class="head">
<paper-item>
<div id="line"><span>Room# {{displayIndex(index)}}</span></div>
<template is='dom-if' if='{{displayIndex != 1}}'>
<paper-button toggles class=button on-click="deleteRoom"><img src="trash.png" height="20px" width="20px"></paper-button>
</template>
</paper-item>
</div>
<choice-form room="{{displayIndex(index)}}">{{ item.room }}</choice-form>
</template>
</form>
I would create a new array that only contains the first room (room#1) and on button click add room#2 to that array and then use this array in dom-repeat instead of rooms.
Your example contains a binding expression inside dom-if (i.e., if="{{displayIndex != 1}}"), but that's currently not supported in Polymer. You'll need to use a computed binding/property instead.
I assume rooms initially contains one item, and there's a button that adds more items to the array.
This is what that code would look like:
HTMLImports.whenReady(() => {
Polymer({
is: 'x-foo',
properties: {
rooms: {
type: Array,
value: () => ['King']
},
_isDeleteHidden: {
type: Boolean,
computed: '_lte(rooms.length, 1)'
}
},
_lte(a, b) {
return a <= b;
},
_inc(index) {
return index + 1;
},
_deleteRoom(e) {
this.splice('rooms', e.model.index, 1);
},
_addRoom() {
this.push('rooms', this._getRandomRoom());
},
_getRandomRoom() {
const ROOMS = ['King', 'Queen', 'Double', 'Standard'];
return ROOMS[randInt(0, ROOMS.length)]
}
});
});
function randInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
<head>
<base href="https://polygit.org/polymer+1.7.1/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-button/paper-button.html">
<link rel="import" href="paper-item/paper-item.html">
<link rel="import" href="paper-icon-button/paper-icon-button.html">
<link rel="import" href="iron-icons/iron-icons.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<paper-button on-tap="_addRoom">Add Room</paper-button>
<template is="dom-repeat" items="[[rooms]]">
<paper-item>
<span>Room #[[_inc(index)]] ([[item]])</span>
<paper-icon-button hidden="[[_isDeleteHidden]]" icon="delete" on-tap="_deleteRoom"></paper-icon-button>
</paper-item>
</template>
</template>
</dom-module>
</body>
codepen
Is not very clear, looks you need just to do
var myRommObject = {....your-properties};
this.push('rooms',myRommObject);
inside the event handler of your button click
have a look here and here
I got the answer for my own question.
You just have to call add function once in ready method.
Following is a code.
ready: function () {
// For default first Room.
this.push('rooms', { room: "" });
this.roomCount = this.roomCount + 1;
},
addRoom: function () {
this.push('rooms', { room: "" });
this.roomCount = this.roomCount + 1;
},

Error while parsing JSON string using JQuery

I am trying to read values from JSON string and display some of it's values using JavaScript alert() statement. But I am getting following exception in the console.
Please guide.
Console Exception
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
...dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){...
at jquery.min.js(line 4, col 5304)
process.js
$(document).ready(function () {
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
console.log(json);
$.each($.parseJSON(json), function (idx, obj) {
alert(obj.name);
});
});
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='${studentsJson}'></div>
</body>
</html>
View Page Source of home.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
</body>
</html>
Since jQuery 1.6 the .data() method parses the values, so remove the $.parseJSON(). You are parsing the object not string that causing the error here. Also check - Why is jQuery automatically parsing my data-* attributes?
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string. ( Taken from https://api.jquery.com/data/ )
$(document).ready(function() {
//static message
var msg = "Hello World from JQuery!";
$("#mydiv").text(msg);
//dynamic message processing for displaying value in div element
var students = $("#studentDiv").data("students");
$("#studentDiv").text(students);
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
// change value here ---------------^------^------
console.log(json);
$.each(json, function(idx, obj) {
alert(obj.name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
From JQuery:
<div id="studentDiv" data-students="[Student{id=1, name=Jack}, Student{id=2, name=Jill}]"></div>
From JQuery (JSON):
<div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
The data you get is an Array of objects. You just have to iterate over it, without having to parse it again. Also, correct attribute name.
var json = $("#studentJsonDiv").data("students-json");
$.each(json, function (idx, obj) {
alert(obj.name);
});
You need to use students-json in data because that is where you have your json data
var json = $("#studentJsonDiv").data("students-json");
$.each($.parseJSON(json), function(idx, obj) {
alert(obj.name);
});
If you're parsing
[Student{id=1, name=Jack}, Student{id=2, name=Jill}]
it's missing : after Student.

How to create a showdown.js markdown extension

Using the following code, I get working output:
<html>
<head>
<script type="text/javascript" src="/js/showdown.js"></script>
</head>
<body>
<script type="text/javascript">
var converter = new Showdown.converter();
alert(converter.makeHtml('*test* abc'));
</script>
</body>
</html>
Returning <p><em>test</em> abc</p>
I would now like to add an extension. The github page suggests this can be done with:
<script src="src/extensions/twitter.js" />
var converter = new Showdown.converter({ extensions: 'twitter' });
However, modifying my code to:
<html>
<head>
<script type="text/javascript" src="/js/showdown.js"></script>
<script type="text/javascript" src="/js/twitter.js"></script>
</head>
<body>
<script type="text/javascript">
var converter = new Showdown.converter({ extensions: 'twitter' });
alert(converter.makeHtml('*test* abc'));
</script>
</body>
</html>
Produces the error
"Uncaught Extension 'undefined' could not be loaded. It was either not found or is not a valid extension."
Adding the following code (as listed under the Filter example)
var demo = function(converter) {
return [
// Replace escaped # symbols
{ type: 'lang', function(text) {
return text.replace(/\\#/g, '#');
}}
];
}
Produces an error Uncaught SyntaxError: Unexpected token (
I would like to create an extension like this one https://github.com/rennat/python-markdown-oembed to interpret a ![video](youtube_link), but it's unclear how to begin adding this support.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']});
converter.makeHtml('whatever #meandave2020');
// output "<p>whatever #meandave2020</p>"
I submitted a pull request to update this.
The way we write extensions has changed, I found some help with the following filter example : http://codepen.io/tivie/pen/eNqOzP
showdown.extension("example", function() {
'use strict';
return [
{
type: 'lang',
filter: function(text, converter, options) {
var mainRegex = new RegExp("(^[ \t]*:>[ \t]?.+\n(.+\n)*\n*)+", "gm");
text = text.replace(mainRegex, function(match, content) {
content = content.replace(/^([ \t]*):>([ \t])?/gm, "");
var foo = converter.makeHtml(content);
return '\n<blockquote class="foo">' + foo + '</blockquote>\n';
});
return text;
}
}
]
});

Array of objects of array, how to access the invidual element without using property names?

I wanted to calculate the average of the innermost arrays as mentioned below without using names of the properties. Is there a way out. I am using javascript. Currently using this syntax, i am getting the array is not defined.
average.js
var data=
[
{
"load":[1,2,3],
"network":[5,6,7]
},
{
"load":[10,11,12],
"network":[14,15,16]
}
]
// I want to calculate the average for each of the properties 'load','network' and many more....
function avg(i)
{
for(j=0;j<data[i].length;j++)
{
sum=0;
for(k=0;j<data[i][j].length;k++)
{
sum+=data[i][j][k];// it do not seems correct
}
average=sum/3;
document.write("value "+i+":"+average);//just for testing
}
}
average.html
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script src="average.js"></script>
</head>
<body>
<script>
avg();
</script>
</body>
</html>
Try this
function avg(i)
{
for(j in data[i])
{
sum=0;
for(k=0;k<data[i][j].length;k++)
{
sum+=data[i][j][k];
}
average=sum/3;
document.write("value "+i+":"+average);
}
}
Call it like this
<script>
avg(0); // Index
</script>
Working Fiddle DEMO

Categories

Resources