Simple jquery plugin for converting json to html - javascript

I need to append this json data to an html element.
[
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
How to convert this easily using any plugin.Presently,I couldn't find any simple plugins in jquery,So please help me friends.
Thanks in advance..........

Hi you can use jPut jQuery Plugin (http://plugins.jquery.com/jput/)
Create a HTML jPut Template
<div jput="template">
{{website}}
</div>
<div id="main">
</div>
<script>
$(document).ready(function(){
var json=[{"website":"google","link":"http://google.com"},
{"website":"facebook","link":"http://fb.com"}];
$('#main').jPut({
jsonData:json, //your json data
name:'template' //jPut template name
});
});
</script>

jPut is easy to use comparing to normal parsing.
if there is lots of data to be appended it is very difficult to append using $.each loop.
in jPut just need to create template & to print the data just put the object name in {{}}.

With jQuery, you could do something like this:
data = $.parseJson(json);
$.each(data, function(key, obj) {
htmlElement = $(''+website+'');
$('body').append(htmlElement);
})

Why use a plugin for this? No need to write a plugin to go around this. Just simply loop it through & do what you wan't with the data. Here is an example:
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
var html = '';
$.each(data, function (index, item) {
html += '' + item.website + '';
});
$('body').append(html);

If you're expecting it to be an anchor tag then -
Html -
<div id="siteContainer"></div>
JS-
var sites = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
var $container = $('siteContainer');
$(sites).each(function(item, index){
var name = item['website'];
var link = item['link'];
var anchorTag = '' + name + '');
$container.appendTo(anchorTag);
});

NO need plugin, simply iterate with each function and append anchor tag with any selector tag.
var links = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
$.each(links, function(index, object){
$("<a></a>").attr("href", object.link).
text( object.website).css("margin", "5px").appendTo("body");
})

no plugin needed, can be done without jquery too
<div id="container">
</div>
<script>
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
document.getElementById('container').innerHTML = ''+data[0]['website']+' >> '+data[0]['link']+' <br> '+data[1]['website']+' >> '+data[1]['link']
</script>

Related

Combine multiple elements and append result to a div

function setParagraph(paraList) {
$.each(paraList, function (i, field) {
var pElement = document.createElement('p');
$(pElement).text(field);
//a line that combines the p elements like so:
//<p>First para</p>
//<p>Second para</p>
});
return //all elements for append;
}
I am trying to write code with minimum number of lines to return a "collection" of p elements that needs to be appended to the following div:
$("#somediv").append(setParagraph(jsonValue));
To produce:
<div id="somediv">
<p>First para</p>
<p>Second para</p>
</div>
The method setParagraph is passed json string with collection of string items that are translated into p elements in the method.
I have tried pushing the elements into an array but I don't think that is the right way to go.
Also, I do not wish to use string concatenation in the loop to produce the desired results, unless of course that is the only best way to handle it.
EDIT:
The below works but as I said I am looking for some other solution besides array:
function setParagraph(paraList) {
var arrElements = [];
$.each(paraList, function (i, field) {
var $pElement = $("<p/>").text(field);
arrElements.push($pElement);
});
return arrElements;
}
var jsonValue = ["First para","Second para"];
$("#somediv").append(setParagraph(jsonValue));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv">
</div>
Shorter
const par = ["one", "two", "three"]
$("#somediv").html(par.map(p => $("<p>", { text: p })))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv"></div>
You can use $.map(..) for that, here is an example:
function setParagraph(paraList) {
return $.map(paraList, function(item) {
return $("<p>", {
text: item
});
});
}
$("#somediv").append(setParagraph(["one", "two", "three"]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv"></div>
I've created a simple fiddle example that I think would suit your needs. It works in a different way, a little bit at least, but with a bit of changing you'd get your desired result.
Here's the fiddle: https://jsfiddle.net/fkoLn4v9/
Here's the code:
// index.js
const paragraphsCollection = [
{
tag: 'p',
content: 'This is the first parargraph',
},
{
tag: 'p',
content: 'This is the second paragraph',
},
];
const setParagraph = (parentElem, contentData) => {
contentData.forEach(({ tag, content }) => {
const domElem = document.createElement(tag);
domElem.innerText = content;
parentElem.appendChild(domElem);
});
};
const divElem = document.querySelector('.parentDiv');
setParagraph(divElem, paragraphsCollection);
HTML:
<div class="parentDiv"></div>

how to get class name of all tags of json using jquery

I have a JSON data and i want to list all attributes of class name inside divs and inner divs and tags.
Sample JSON DATA :
[
{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}
]
I have used children() but it is not taking inner class name, output i got is
main-header dark-bg row space-9 hide-md using the below code by taking json data in a variable
if($(t).children().length > 0){
console.log($(t).children().length);
//OUTPUT SHOWING 2
}
To achieve this you can use some relatively straightforward recursion to traverse down the DOM tree within the HTML string, something like this:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push($(this).prop('class'));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var classes = buildClassArray($(data[0].Field1));
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that if you want multiple classes on a single element to appear within their own entity in the array, simply split() the class string before you push it to the array:
var data = [{
"Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\" title=\"DWS Homepage\"><img src=\"/globalassets/images/logos/dws_logo_global.svg\" class=\"icon-svg hide-for-print\" alt=\"dws_logo_global\"></a>\n\t\t</div>\n\n\t\t<div class=\"space-9 hide-md\"></div>\n\t</header>"
}]
function buildClassArray($el, arr) {
arr = arr || [];
$el.each(function() {
arr.push(...$(this).prop('class').split(' '));
$(this).children().each(function() {
buildClassArray($(this), arr);
})
});
return arr;
}
var $el = $(data[0].Field1);
var classes = buildClassArray($el);
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

how to get json data with the following format?

I've a json file to get a list of test results.
Below is the json file. And a short snippet of the jquery.
I am trying to get the test id from the json and display them as a unordered list.
How can I do that?
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
}
]
<script type="text/javascript">
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data)
{
alert(data[i].[Test].id);
}
});
</script>
You're missing the quotes around Test, it should be a string and remove the dot before it.
alert(data[i]['Test'].id);
also your json is not valid, remove the trailing , after each book_type.
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
}
]
http://jsfiddle.net/ef7Nq/
Loop through the items in the array and append nodes for each id.
$.each(obj, function (i, item) {
ul.append($('<li>' + item.Test.id + '</li>'));
});
fiddle here
You can do data[i]['Test'].id or data[i].Test.id since there's no space in the name.
You can try this:
alert( data[i].Test.id );
Full Code:
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data) {
alert( data[i].Test.id );
}
});
Demo
Try
Fiddle Demo
var ul = '';
for (var i in data)
{
ul += '<li>'+data[i]['Test'].id+'</li>';
}
$('#el').append($('<ul/>').html(ul));

jQuery remove don't work when run over maped set

I have code like this:
$('#mb-history').on('click', '#post-edit .buttons .delete', function() {
var files = $('.files input:checked').map(function() {
return $(this).closest('.file');
});
var ids = files.map(function() {
return $(this).data('id');
}).get();
console.log(ids);
files.remove(); // this don't work
return false;
});
and files.remove() don't work the element stay in the DOM. (console.log show array with element I've selected). My html look like this:
<div class="files ui-helper-clearfix" style="display: block;">
...
<div class="file" data-id="13835">
<img src="/thumb.php?src=moja-budowa%2F611%2FMB_Z3_611_13835.jpg&size=90&height=64&nologo" alt="">
<input type="checkbox">
</div>
...
</div>
What's wrong with my code? I'm using jquery-1.8.2.
JSFIDDLE
I found, instead of map I can just put closest after set:
var files = $('.files input:checked').closest('.file')
You must have files references for removing or any other action.. $.map() create a new array. Change:
var files = $('.files input:checked').map(function() {
return $(this).closest('.file');
});
to
var files = $('.files input:checked').parent();
files
[
e.fn.e.init[1]
0: div.file
context: input
length: 1
prevObject: e.fn.e.init[1]
selector: ".closest(.file)"
__proto__: Object[0]
]
files[0].remove()

Suggest any Good mustache document

Suggest me any good mustache doc. Also i want to know in a mushtach loop how do i get the count or the loop no. I mean how can i do a for loop in mustache.
In the below code i wish to change the id in every loop
<script src="http://github.com/janl/mustache.js/raw/master/mustache.js"></script>
<script>
var data, template, html;
data = {
name : "Some Tuts+ Sites",
big: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
url : function () {
return function (text, render) {
text = render(text);
var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
return '' + text + '';
}
}
};
template = '<h1> {{name}} </h1><ul> {{#big}}<li id="no"> {{#url}} {{.}} {{/url}} </li> {{/big}} </ul>';
html = Mustache.to_html(template, data);
document.write(html)
</script>
<body></body>
You can't get at the array index in Mustache, Mustache is deliberately simple and wants you to do all the work when you set up your data.
However, you can tweak your data to include the indices:
data = {
//...
big: [
{ i: 0, v: "Nettuts+" },
{ i: 1, v: "Psdtuts+" },
{ i: 2, v: "Mobiletuts+" }
],
//...
};
and then adjust your template to use {{i}} in the id attributes and {{v}} instead of {{.}} for the text:
template = '<h1> {{name}} </h1><ul> {{#big}}<li id="no-{{i}}"> {{#url}} {{v}} {{/url}} </li> {{/big}} </ul>';
And as an aside, you probably want to include a scheme in your url:
url : function () {
return function (text, render) {
text = render(text);
var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
return '' + text + '';
//---------------^^^^^^^
}
}
Demo: http://jsfiddle.net/ambiguous/SFXGG/
Expanding on #mu's answer, you could also keep an index in the data object and have the template refer to it and the function increment it. So you wouldn't need to add i to each item.
see demo : http://jsfiddle.net/5vsZ2/

Categories