I'm trying to make an automatic news feed on a project website, where all the posts are put into a JSON file and then formatted on the news page accordingly. I've finally figured out how to get the json parser to show SOMETHING but that something is just a bunch of "undefined" bits all over the page. What am I doing wrong?
The jquery/html snippet
<script>
$.getJSON("js/news.json", function (data) {
$.each(data.posts, function (val) {
var title = val.title;
var date = val.date;
var content = val.content;
$("#newscontainer").append('<div><h1>' + title + '</h1><h2>' + date + '</h2><p>' + content + '</p></div>');
});
});
</script>
<div id='newscontainer'>
</div>
The JSON snippet
{
"posts": [
{
"title": "title1",
"date": "8302014",
"content": "LotsoftextLotsoftext"
},
{
"title": "title2",
"date": "8312014",
"content": "CopiousquantitiesoftextCopiousquantitiesoftext"
},
{
"title": "title3",
"date": "8322014",
"content": "onlyalittletext"
}
]
}
val in your code is the index, you should use the second argument of the callback.
$.each(data.posts, function (index, val) {
You can also use the this keyword.
Try this one :
var post_title = val.title;
var post_date = val.date;
var post_content = val.content;
var divTag = document.createElement("div");
newscontainer.appendChild(divTag);
var h1Tag = document.createElement("h1");
h1Tag.innerHTML = post_title;
newscontainer.appendChild(h1);
var h2Tag = document.createElement("h2");
h2Tag.innerHTML = post_date;
newscontainer.appendChild(h2);
var pTag = document.createElement("p");
pTag.innerHTML = post_content;
newscontainer.appendChild(p);
You can use the each() function on your list:
$(data.posts).each(function() {
var $this = this;
$("#newscontainer").append('<div><h1>' + $this.title + '</h1><h2>' + $this.date + '</h2><p>' + $this.content + '</p></div>');
});
Related
I would like to grab a data from JSON array, which looks like below, and so this.responceText returns this data. And I try to use the data from my Javascript code, but it is not working, and also there is no error message. Where is wrong in my code? Thanks.
{"0":{"folder":"callofthewild","title":"Call of the Wild"},"1":{"folder":"2001spaceodyssey","title":"2001: A Space Odyssey "},"2":{"folder":"hobbit","title":"The Hobbit"},"4":{"folder":"pokemon","title":"I Choose You! (Pokemon Chapter Books)"},"5":{"folder":"alannathefirstadventure","title":"Alanna: The First Adventure (Song of the Lioness #1)"}}
part of my javascript;
var books = JSON.parse(this.responseText);
for (var i = 0; i < books.length; i++) {
var book = document.createElement("div");
var text = document.createElement("p");
var image = document.createElement("img");
image.src = "books/" + books.i.folder + "/cover.jpg";
text.innerHTML = books.i.title;
book.appendChild(image);
book.appendChild(text);
document.getElementById("allbooks").appendChild(book);
}
Since your JSON is an object (not an array), you can use Object.keys() to get all its keys and then iterate over its keys to get the appropiate values:
var books = JSON.parse(this.responseText);
Object.keys(books).forEach(function (index) {
var book = books[index];
var div = document.createElement("div");
var text = document.createElement("p");
var image = document.createElement("img");
image.src = 'books/' + book.folder + '/cover.jpg';
text.innerHTML = book.title;
div.appendChild(image);
div.appendChild(text);
document.getElementById('allbooks').appendChild(div);
});
Your json is not an array.. so your .length will be undefined
$.each(books, function(i, n) {
var book = document.createElement("div");
var text = document.createElement("p");
var image = document.createElement("img");
alert(books[""+i+""].folder)
image.src = "books/" + n.folder + "/cover.jpg";
text.innerHTML = n.title;
book.appendChild(image);
book.appendChild(text);
document.getElementById("allbooks").appendChild(book);
});
A literal object hasn't length property.
var books = {
"0": {
"folder": "callofthewild",
"title": "Call of the Wild"
},
"1": {
"folder": "2001spaceodyssey",
"title": "2001: A Space Odyssey "
},
"2": {
"folder": "hobbit",
"title": "The Hobbit"
},
"4": {
"folder": "pokemon",
"title": "I Choose You! (Pokemon Chapter Books)"
},
"5": {
"folder": "alannathefirstadventure",
"title": "Alanna: The First Adventure (Song of the Lioness #1)"
}
};
Object.keys(books)
.map(key => books[key])
.forEach(book => {
var div = document.createElement("div");
var text = document.createElement("p");
var image = document.createElement("img");
image.src = "books/" + book.folder + "/cover.jpg";
text.innerHTML = book.title;
div.appendChild(image);
div.appendChild(text);
document.getElementById("allbooks").appendChild(div);
});
<div id="allbooks"></div>
You are using JSON Object and not an array. And 'length' is not a property for Array.
So it iterate over this, you can use:
for (var bookKey in books) {
var book = books[bookKey];
// And create html content here
}
It's my second day on this project :\
I'm trying to create is : creating a new <a> element with a new href and id attributes in for loop so that I can get each output of the API as a link.
This is my JS Code
var one;
var two;
var hoba;
$(document).ready(function() {
$("#inp").keyup(function() {
hoba = $(this).val();
});
$("#but").on("click", function() {
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;
$.getJSON(app, function(data) {
for (i = 0; i < data.query.search.length; i++) {
console.log(app);
one = $("<a></a>").text(data.query.search[i].title);
//var _href = $("a").attr("href");
$("a").attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
$("a").attr("id", data.query.search[i].title);
two = document.createElement("p");
two.innerHTML = data.query.search[i].snippet;
$("body").append(one, two);
}
});
});
});
Use same object to set attributes
one = $("<a></a>");
one.text(data.query.search[i].title);
one.attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
one.attr("id", data.query.search[i].title);
Use jQuery( html, attributes ) to create HTML element.
var anchor = $("<a></a>", {
"text": data.query.search[i].title,
"href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
"id": data.query.search[i].title
});
$("body").append(anchor);
$(document).ready(function() {
$("#inp").keyup(function() {
hoba = $(this).val();
});
$("#but").on("click", function() {
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;
$.getJSON(app, function(data) {
for (i = 0; i < data.query.search.length; i++) {
var anchor = $("<a></a>", {
"text": data.query.search[i].title,
"href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
"id": data.query.search[i].title
});
var p = $("<p></p>", {
"html": data.query.search[i].snippet
});
$("body").append(anchor);
$("body").append(p);
}
});
});
});
You should to do minor changes in your code as below.
Change code are in between
// Changes Code Start and // Changes Code End
var one;
var two;
var hoba;
$(document).ready(function(){
$("#inp").keyup(function(){
hoba = $(this).val();
});
$("#but").on("click",function(){
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch="+hoba;
// Changes Code Start
$.getJSON(app,function(data){
for(i=0; i<data.query.search.length; i++){
console.log(app);
var dataAppend;
var title = data.query.search[i].title;
var href = 'https://www.wikipedia.org/wiki/' + data.query.search[i].title;
var id = data.query.search[i].title;
dataAppend = "<a href='"+href+"' id='"+id+"'>"+title+"</a>";
dataAppend += "<p>"+data.query.search[i].snippet+"</p>";
// \"
$("body").append(dataAppend);
}
});
// Changes Code End
});
});
I'm trying to when I press button (Get Value) to set the size of checkboxes to text. I make the variable (numAll) global, and convert toString, but still not working. any idea to solve the solution?
Demo
Jquery:
$(function () {
// Click function to add a card
var $div = $('<div />').addClass('sortable-div');
$('<label>Title</label><br/>').appendTo($div);
$('<input/>', {
"type": "text",
"class": "ctb"
}).appendTo($div);
$('<input/>', {
"type": "text",
"class": "date"
}).appendTo($div);
$('<input/>', {
"type": "text",
"class": "Cbox"
}).appendTo($div);
var cnt = 0,
$currentTarget;
$('#AddCardBtn').click(function () {
var $newDiv = $div.clone(true);
cnt++;
$newDiv.prop("id", "div" + cnt);
$newDiv.data('checkboxes', []);
$('#userAddedCard').append($newDiv);
// alert($('#userAddedCard').find("div.sortable-div").length);
});
$("#Getbtn").on("click", function () {
var val = $("#customTextBox").val();
$currentTarget.find(".ctb").val(val);
$currentTarget.find(".date").val($("#datepicker").val());
var Cboxval = numAll;
var st = console.toString(Cboxval);
$currentTarget.find(".Cbox").val(st);
$currentTarget.data('checkboxes', $('#modalDialog').data('checkboxes')); /* Copy checkbox data to card */
//$('#modalDialog').dialog("close");
});
var numAll;
function updateProgress() {
var numAll = $('input[type="checkbox"]').length;
var numChecked = $('input[type="checkbox"]:checked').length;
if (numAll > 0) {
var perc = (numChecked / numAll) * 100;
$("#progressbar").progressbar("value", perc)
.children('.ui-progressbar-value')
.html(perc.toPrecision(3) + '%')
.css("display", "block");
}
}
You should use .toString() method on a Number Object:
var st = Cboxval.toString();
Otherwise I can't find where are you defining the numAll variable, so I had to replace
var Cboxval = numAll;
with:
var Cboxval = numAll === undefined ? 0 : numAll;
in order to be able to perform mys tests.
Here you have an updated version of your JS fiddle.
I have this following JSON data snippit:
{"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]}
How do I populate the following html elements with this data:
<div class="news-story">
<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>
</div>
I want accomplish this with Javascript not jQuery.
Loop through them and use the DOM functions:
var news = document.getElementsByClassName("news-story")[0];
var items = json.items;
for(var i = 0; i < items.length; i++) {
var h5 = document.createElement("h5");
h5.innerHTML = items[i].title;
news.appendChild(h5);
var p = document.createElement("p");
p.innerHTML = items[i].author;
news.appendChild(p);
}
http://jsfiddle.net/AWRAW/
getElementsByClassName will not work in versions of IE prior to 9. If you need to support those though, you're really better off using jQuery.
var div = document.getElementsByClassName('news-story')[0],
h5 = div.getElementsByTagName('h5'),
p = div.getElementsByTagName('p'),
data = JSON.parse( my_JSON_data );
data.items.forEach(function(v,i) {
h5[i].innerHTML = v.title;
p[i].innerHTML = "By: " + v.author;
});
JSFIDDLE DEMO
If you need to support older browsers, you can use a typical for statement instead of the forEach method.
for( var i = 0; i < data.items.length; ++i ) {
var v = data.items[i];
h5[i].innerHTML = v.title;
p[i].innerHTML = "By: " + v.author;
}
And I'd suggest using an ID instead of a class for the news-story element, so you can use getElementById instead (unless of course you have several of them).
If that's impossible, you may want to use a compatibility function from MDN for getElementsByClassName.
If you needed to create the inner elements, then here's one way:
var div = document.getElementsByClassName('news-story')[0],
data = JSON.parse( my_JSON_data ),
html;
html = data.items.map(function(v,i) {
return '<h5>' + v.title + '</h5>' +
'<p>By: ' + v.author + '</p>';
}).join('');
div.innerHTML = html;
JSFIDDLE DEMO
#Xeon06 shows how in his answer using createElement(), which is arguably a better approach.
Here's how I'd do it:
var div = document.getElementsByClassName('news-story')[0],
frag = document.createDocumentFragment(),
data = JSON.parse( my_JSON_data );
data.items.forEach(function(v,i) {
frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
});
div.appendChild( frag );
JSFIDDLE DEMO
And of course you can modify it to use a for statement instead:
var div = document.getElementsByClassName('news-story')[0],
frag = document.createDocumentFragment(),
data = JSON.parse( my_JSON_data );
for( var i = 0; i < data.items.length; ++i ) {
var v = data.items[i];
frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
}
div.appendChild( frag );
The benefit of using a documentFragment is that you can do a single append to the DOM via the fragment instead of multiple appends. This gives better performance, especially if you have a large set of data.
Better late than never... I recently made a lib to do just this!
FragBuilder is the library.. usage is pretty simple: for the example you have posted you would need to change around the JSON a bit to make it a bit more semantic...
var frag = [{"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]}];
would become
var frag = [ { "childNodes" : [ { "childNodes" : [ { "textContent" : "sample 1" } ],
"tagName" : "H5"
},
{ "childNodes" : [ { "textContent" : "By: author 1" } ],
"tagName" : "P"
},
{ "childNodes" : [ { "textContent" : "sample 2" } ],
"tagName" : "H5"
},
{ "childNodes" : [ { "textContent" : "By: author 2" } ],
"tagName" : "P"
}
],
"className" : "news-story",
"tagName" : "DIV"
} ];
then you would generate a DocumentFragment by calling FragBuilder(frag)
There is also a reverse function if you find it easier to template using HTML then convert to JSON https://gist.github.com/2313580 (note, whitespace between tags is not handled and will cause failures)
I've found that the most reliable way to create DOM elements is using the element.innerHTML property. Basically you'd have a DIV or SPAN at the place at the place on the page where you want to render the new HTML. Then you'd grab that span in javascripting using document.getElementById("DIV-ID") and then set the innerHTML property of the DIV to the new HTML that you would generate from the JSON object. There are a bunch of other JavaScript functions to create elements, but I've found that they're not always reliable and don't always have the best cross-browser support.
http://www.w3schools.com/jsref/prop_html_innerhtml.asp
Sample with no jQuery:
<html>
<head>
<title>test</title>
</head>
<body>
<div class="news-story">
<h5>sample 1</h5>
<p>By: author 1</p>
<h5>sample 2</h5>
<p>By: author 2</p>
</div>
<script type="text/javascript">
var json = {
"items": [
{
"title": "sample x",
"author": "author x"
},
{
"title": "sample y",
"author": "author y"
}
]
};
var bindDataToHTML = function(data, element) {
var h5 = null;
var p = null;
h5 = element.getElementsByTagName("h5");
p = element.getElementsByTagName("p");
h5[0].innerText = data.items[0].title;
h5[1].innerText = data.items[1].title;
p[0].innerText = data.items[0].author;
p[1].innerText = data.items[1].author;
};
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) { retnode.push(elem[i]); }
}
return retnode;
};
// For sample purpose, let's imagine this method is a callback
// for a request that provides you with your json data
var doRequest = function() {
var data = json;
var element = null;
var x = document.getElementsByClassName("news-story");
if((null != x) && (0 < x.length)) {
element = x[0];
}
bindDataToHTML(data, element);
};
(function() {
doRequest();
})();
</script>
</body>
</html>
Try JsRender and JsViews or moustache/ember
$(document).ready(function () {
loadfunctionAjax();
});
var loadfunctionAjax = function () {
$.ajax({
type: 'GET',
url: '/Site/SocialLink',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var HTML = '';
for (var i = 0; i < data.length; i++) {
item = data[i];
HTML += '<li><a class="" target="_blank" href="' + item.FALink + '"><i class="fa ' + item.FAIcon + '"></i>' + item.Name + '</a ></li > ';
}
$('#footerSocialNav').append(HTML);
}
});
}
This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have the following JSON structure:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
How do I iterate over it using JavaScript?
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
note: the for-in method is cool for simple objects. Not very smart to use with DOM object.
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Use for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (var car of mycars)
{
document.write(car.name + "<br />");
}
Result:
Susita
BMW
Please let me know if it is not easy:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
If this is your dataArray:
var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];
then:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var CLASS = this.class;
});
Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
RESULT: John Doe 25
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
You can use a mini library like objx - http://objx.googlecode.com/
You can write code like this:
var data = [ {"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}];
// alert all IDs
objx(data).each(function(item) { alert(item.id) });
// get all IDs into a new array
var ids = objx(data).collect("id").obj();
// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()
There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary
With nested objects, it can be retrieve as by recursive function:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
where as events is json object.
Marquis Wang's may well be the best answer when using jQuery.
Here is something quite similar in pure JavaScript, using JavaScript's forEach method. forEach takes a function as an argument. That function will then be called for each item in the array, with said item as the argument.
Short and easy:
var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"} ];
results.forEach(function(item) {
console.log(item);
});
this is a pure commented JavaScript example.
<script language="JavaScript" type="text/javascript">
function iterate_json(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
hr.open("GET", "json-note.php", true);//this is your php file containing json
hr.setRequestHeader("Content-type", "application/json", true);
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("myDiv");//myDiv is the div id
for (var obj in data){
results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>";
}
}
}
hr.send(null);
}
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here
var jsonString = `{
"schema": {
"title": "User Feedback",
"description": "so",
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
},
"options": {
"form": {
"attributes": {},
"buttons": {
"submit": {
"title": "It",
"click": "function(){alert('hello');}"
}
}
}
}
}`;
var jsonData = JSON.parse(jsonString);
function Iterate(data)
{
jQuery.each(data, function (index, value) {
if (typeof value == 'object') {
alert("Object " + index);
Iterate(value);
}
else {
alert(index + " : " + value);
}
});
}
Iterate(jsonData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another solution to navigate through the JSON document is JSONiq (implemented in the Zorba engine), where you can write something like this:
let $doc := [
{"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class (: gets the value associated with "class" :)
You can run it on http://public.rumbledb.org:9090/public.html