I am trying to add json object for html arrtibute content but not working.I have tried many ways but I do not know how to set that.if any one know about that please help to resolve this issue.
javascript:
var validatorValue='{
"picker":{
"allow":
{
"message": "Content loram ipsom"
},
"past":
{
"message": "lorem issom"
}
}
}' ;
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html("<div input="true" validator='+validatorValue+' date-restrict='+daterestrictValue+' my-input='+myinputValue+'></div>");
The main issue with your code (aside from line-breaks in string literals) it the mis-matched quotes in the HTML string you build. However, even after correcting those you will have issues placing serialised JSON within attributes as it too contains double quotes which will break the HTML syntax.
Also note that you're creating non-standard attributes in the HTML you create which may cause unexpected issues in your UI and JS.
An alternative way to approach this is to work with the values as objects (instead of strings). You can use jQuery to set the data of the element using those objects, like this:
var validatorValue = { "picker": { "allow": { "message": "Content loram ipsom" }, "past": { "message": "lorem issom" } } }
var daterestrictValue = { 'range': { 'start': '2019-10-30', 'end': '2019-12-30' } }
var myinputValue = { 'date': 'tomorrow' };
var $newDiv = $('<div data-input="true">Click me</div>').appendTo('#mydiv');
$newDiv.data({
"validator": validatorValue,
"date-restrict": daterestrictValue,
"my-input": myinputValue
});
// for testing
$('#mydiv div').on('click', function() {
console.log($(this).data('validator'));
console.log($(this).data('date-restrict'));
console.log($(this).data('my-input'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
this code save object in html element.
good luck
var validatorValue="{ 'picker':{'allow':{'message': 'Content loram ipsom'},'past':{'message': 'lorem issom'}}}";
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html(`
<div input='true' validator="${validatorValue}" date-restrict="${daterestrictValue}" my-input="${myinputValue}">ggg</div>`);
Related
I have a problem with JSON data. I want to add a span element inside a string, but it doesn't work. How to ''escape'' string? Below is an example.
{
"text": "Copyright©2020 <span class="test">Gamepix</span> All Rights Reserved."
}
If you're using Typescript you can use in your HTML file [innerHTML].
Example:
<div [innerHTML]="text"></div>
in your typescript file:
text: string = "some text here <span class='yellow'>six pieces</span>, and here";
and in your .scss file:
::ng-deep .yellow {
color: #f5dc27;
}
I know I'm a bit late to this question but I just worked this out for myself! The "render" function takes my data in the JSON key "data" and returns the data in "dataname" as well as my desired html tag (span). Hope this helps!
{
"data": "dataname", render: function (data) {
return data + '<span></span>';
}
},
"Other data keys to follow"
{
},
I have a one-file website... We all know bandwidth and internet are... yeah... That's why I only render parts of user interface when needded. Now I wanna take a step further and use JSON to store small parts of my website (trees of html elements) and generete the actual HTML on demand.
But I'm struggling to figure out how to "convert" the JSON object into plain old HTML. I found many topics and answers on how to achieve this, but none of those solved problems. I need a solution that could generate trees with ANY number of chid elements, inside of child elements and so on... All these solutions used .innerHTML which could literally void all my event handlers. I found nothing I wouldn't know already...
The JSON notation would look like this:
var htmlTree = {
'type': 'section',
'attr': {
'id': 'someID',
'class': 'someClass'
},
'content': 'section name',
'children': [
{
'type': 'h1',
'attr': {
'class': 'heading'
},
'content': 'Heading',
'children': [
{
'type': 'span',
'content': 'text'
},
{
'type': 'span',
'content': 'more text'
}
]
}
]
}
And the result would look like this:
<section id="someID" class="someClass">
section name
<h1 class="heading">
Heading
<span>text</span>
<span>more text</span>
</h1>
</section>
Does anybody know a solution to this problem? I really don't want to use any frameworks or libraries. I know it's a little hard to do something like this, that's why I'm asking here...
Bandwidth is cheap nowadays as the server supports gzip it takes even less. Why combine with more engaging Json and libraries to create HTML?
Instead of processing JSON, inject ready (parts) html - loaded via Ajax.
Try
http://www.json2html.com
You can try something like this but this make sense only if you have many same rows (and your data is really simple).
<html>
<body>
<div id="ct"></div>
<script>
var data = [{
"id" : 1,
"f" : "Arya",
"l" : "Stark"
},
{
"id" : 1,
"f" : "Jon",
"l" : "Snowk"
}];
var parent = document.getElementById("ct");
data.forEach( function (row) {
newDiv = document.createElement("div");
newDiv.innerHTML = "<h1>" + row.f + " " + row.l + "</h1>";
parent.append(newDiv);
})
</script>
</body>
</html>
The JSON.parse reviver can be used to transform key value pairs in JSON string :
var json = '{"type":"section","attr":{"id":"someID","class":"someClass"},"content":"section name","children":[{"type":"h1","attr":{"class":"heading"},"content":"Heading","children":[{"type":"span","content":"text"},{"type":"span","content":"more text"}]}]}'
var el = JSON.parse(json, function(k, v) {
if (!v.type) return v
var el = document.createElement(v.type)
el.textContent = v.content
for (k in v.attr || {})
el.setAttribute(k, v.attr[k])
for (var c of v.children || [])
el.append('\n', c)
return el
})
document.body.innerHTML = el.outerHTML
console.log( el.outerHTML )
I am trying to POST using PolymerJS ajax-forms and I encounter a weird JSON format error. Can someone tell me why the quotes are missing around the keys? The only workaround I can think of is manually constructing the body with the quotes around the keys.
Code Snippet :
How I receive the values (rest are the same with the ids changed):
<div>
<paper-input label="Title" id="course-title" floatingLabel value="{{item.title}}"></paper-input>
</div>
<access-core-ajax
auto = "false"
url="domain/courses"
response="{{response}}"
method="post"
id="postCourse"
contentType="application/json"
headers='{"Accept": "application/json", "Content-Type":"application/json"}',
body = "{{item}}">
<template id="get-response-template" repeat="{{item in response.entries}}">
<p>Errors</p>
</template>
</access-core-ajax>
Polymer('create-new-course-page',{
domReady: function() {
console.log("Log: create-new-courses-page - Looks like we are domReady");
},
created: function() {
console.log("Item initialized");
this.item = {};
this.data={};
},
createNewCourse: function(event) {
console.log("HERE IS BODY", this.item);
this.$.postCourse.go();
}
And the JSON is see on the log:
{
title: "WRU",
// rest of key & values, where the keys are without the ""
}
You need to turn the body into a JSON string first. JSON.stringify can help.
...
createNewCourse: function(e) {
this.$.postCourse.body = JSON.stringify(this.item);
this.$.postCourse.go();
}
You may need to remove the body attribute here. You can also remove that auto attribute since by default it is false.
I'm trying to use a wysiwyg in my angular app. What I want to happen is, I query an end point for an array of objects. Then based on the property name the data inside it gets wrapped into a different html tag. Then all the data is concatenated into a string which gets displayed on a wysiwyg in my app.
So JSON that looks like
[
{
"name": "steve",
"age": 33,
"profile": "http://www.profile.com/steve",
"location": "New York"
},{
"name": "john",
"age": 25,
"profile": "http://www.profile.com/john",
"location": "LA"
},
]
Spits out:
"<b>Steve - New York</b>
<br>
<a href='http://www.profile.com/steve'>Url</a>
<br>
<span>33</span>
<br>
<br>
<b>John - LA</b>
<br>
<a href='http://www.profile.com/john'>Url</a>
<br>
<span>25</span>
<br>
<br>"
While this part isn't Angular specific. I think I need to add this code into a service so that it can be reused whenever I would need it an an app.
I'm not sure what this code would look like. Any ideas?
EDIT: For clarification the reason why I'm doing this is because the page has a WYSIWYG on it. A non-technical user needs to be able to edit the data in the WYSIWYG then click a button and the app exports a PDF. The WYSIWYG requires a single string with HTML tags as does the backend of the app which generates the PDF file.
It seems to me that there's really no reason to reinvent the wheel here... why can't you just use a fully supported WYSIWYG editor like TinyMCE? It's got an angular extension through the Angular-UI project here:
https://github.com/angular-ui/ui-tinymce
Then you could write this in your html:
<textarea ui-tinymce="tinyMceOptions" ng-model="parsedResponse"></textarea>
<button ng-click="convertToPdf()">Y U NO DOWNLOAD PDF?</button>
In your controller (or directive):
$scope.tinyMceOptions = {/*Customize here*/};
$scope.parseMyResponse = function(data) {
// do something with data and return as html string
return data;
};
$http.get('/your/resource/url').success(function(result) {
$scope.parsedResponse = $scope.parseMyResponse(result);
});
$scope.convertToPdf = function() {
// do something with $scope.parsedResponse here to get a PDF
};
Edit:
I guess I didn't get what you were asking exactly at first? If you want it in a service all you have to do is something like:
angular.module('app')
.service('Util', function() {
return {
wrapInTag: function(tagName, value) {
return '<' + tagName + '>' + value + '<' + tagName + '/>';
},
parseMyResource: function(response) {
htmlString = '';
angular.each(response, function(item) {
htmlString += this.wrapInTag('h1', item.title);
htmlString += this.wrapInTag('b', item.id);
// Other manipulation...
});
return htmlString;
}
};
});
Then in your controller:
angular.module('app')
.controller('MyCtrl', function(Util){
// Use Util functions here...
});
I've given you some example code for parsing JSON into HTML strings, but I'm afraid I couldn't be more specific as to how to write it. The logic if your parsing function really depends on what you're trying to accomplish as well as what your data model looks like. There's really no straight-forward way to convert JSON to HTML.
I am getting data from json file, now i want to add it to filteringselect. i tried below code but its not adding, please help me
HTML code==
<select data-dojo-type="dijit/form/FilteringSelect"
id="education"></select>
Javascrip code==
request.get("/json/education.json", {
handleAs: "json"
}).then(function(data) {
var node = dijit.byId('education');
dojo.forEach(data.items, function(desc, index){
node.addOption({
label: desc.name,
value: desc.value
});
});
},
function(error){});
Json code
{
"title":"Education",
"items":[
{"name":"Select Education","value":"0"},
{"name":"B.A", "value":"1"},
{"name":"B.Sc" ,"value":"2"},
...........................
The store of FilteringSelect can be set dynamically, based on the ajax call.
var str = new dojo.store.Memory(optionData);
dijit.byId('widgetId').set('store',str);
But, your json data must be like this:-
var optionData={
data:[
{id:'aaaaaa',name:'aaaaaa'},
{id:'bbbbbb',name:'bbbbbb'}
]
};
The above example will actually replace the store. If, the new data from ajax call need to be appended to the existing options, then
//str is the existing store of FilteringSelect field above
dojo.forEach(result.data, function(optionSet, index){
str.add(optionSet);
});
Note to remember: 'addOption' is available only for Select. Not for FilteringSelect.
I hope this helps:
dijit.byId("select_id").store.root.add(dojo.create("option",{ value: "some", innerHTML: "label of option"}));
To remove the existing elements did just that:
var size = dijit.byId("select_id").store.root.removeChild.length;
for(var i=size; i>=0; i--){ dijit.byId("select_id").store.root.removeChild(dijit.byId("select_id").store.root.children[size-1]);
}