Printing JSON object with jQuery into html - javascript

I have a JSON object that looks like this:
var content = '[{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}]';
And I am trying to edit it with jQuery to display in my div tag with the id of content-view
here is my jquery:
$.each(content, function(t, l){
$('#view-content').appendTo('<div id = "' + l + '">' + t + '</div>');
});
For some reason on my jsFiddle, which is right here: http://jsfiddle.net/gAWTV/
It just comes up blank with the result. Does anyone have any ideas? I am stumped...
---EDIT---
What i would like to do is have everything output into its own div tags like this:
<div id="Apple">John Apple</div>
<div id="Patel">Kumar Patel</div>
<div id="Quinn">Michaela Quinn</div>
etc...

Your content is a string, not an array of objects.
You firstly need to store it as an array, so get rid of the single quotations marks.
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
Unless there is a reason you store it as a string? Then you need to parse it.
var content_object = JSON.parse(content);
Then you can run your code. However, I think you want to "stringify" your JSON. If that's the case you also need to swap t with l, because l is the object. Finally, you want to append, not appendTo. The latter appends the subject to the target you specify, not the other way round (so in your case appendTo appends #view-content to your div you've constructed, which doesn't work).
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + t + '">' + JSON.stringify(l) + '</div>');
});
JSFiddle
Final comment, I would use document fragments to build your list instead of appending the new divs to an existing one in the each loop - that improves performance.
After OP edit:
Change the last snippet to:
$.each(content, function(t, l){
$('#view-content').append('<div id = "' + l.lastname + '">' + l.title + '</div>');
});
Updated JSFiddle

Try this:
var content = [{"title":"John Apple","lastname":"Apple"},
{"title":"Kumar Patel","lastname":"Patel"},
{"title":"Michaela Quinn","lastname":"Quinn"},
{"title":"Peyton Manning","lastname":"Manning"},
{"title":"John Doe","lastname":"Doe"},
{"title":"Jane Lee","lastname":"Lee"},
{"title":"Dan McMan","lastname":"McMan"},
{"title":"Yu Win","lastname":"Win"}];
$.each(content, function(t, l){
$('<div/>',{
id: l,
text:t }).appendTo('#view-content');
});
DEMO

Related

Random quotation mark being inserted into generated onclick html parameter

I'm trying to add parameters to an onclick function when generating HTML via javascript. When I inspect the code it is putting a quotation mark in the onclick function's parameter.
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$("#CatTable").append("<div class='better-table-cell'>" + ArrayOfCategories[a].Name + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].DepartmentName + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].Active + "</div>\
<div class='better-table-cell'>\
<button onclick=OpenUpdateCat(" + ArrayOfCategories[a].CategoryID + "," + ArrayOfCategories[a].Name + ");" + ">Edit</button>\
</div>");
Here is an image of the HTML that is getting generated for the edit button.
The browser is normalising the HTML and putting quote marks around the attribute value.
The problem is that because the attribute value includes spaces, and you didn't put the quote marks in the right spots yourself, the attribute value finishes in the middle of the JavaScript.
The next bit of JS is then treated as a new attribute.
Mashing together strings to generate HTML is fundamentally a bad idea. Ensuring all the right things are quoted and escaped is hard.
Use DOM to generate your HTML instead.
It is a little longer, but clearer and easier to maintain in the long run.
var $cat_table = $("#CatTable");
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Name)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].DepartmentName)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Active)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").append(
$("<button />").text("Edit").on("click", generate_edit_handler(ArrayOfCategories[a].CategoryID, ArrayOfCategories[a].Name))
)
);
}
function generate_edit_handler(cat_id, name) {
return function () {
OpenUpdateCat(cat_id, name);
};
}

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

js/jquery iterate through html elements to dynamically build a string

I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"

jQuery "undefined" prints when appending to html element

I'm making a jQuery MP3 player. The song structure is first generated (including the information about the song), and then the structure is appended to a div using jQuery like this:
function loadFromPlaylist(playlist) {
var songsStructure;
for (var i=0; i<playlist.length; i++) {
songsStructure +=
"<div id='song" + i + "'>" +
"<span class='mpPlaylistArtist'>" + playlist[i].artist + "</span>" +
"<span class='mpPlaylistSong'>" + playlist[i].song + "</span>" +
"<span class='mpPlaylistAlbum'>" + playlist[i].album + "</span>" +
"</div>";
}
$('#mpTracks').append(songsStructure);
}
This works perfectly except for one thing. When the items are displayed in the browser, a string ("undefined") is printed above the songs, like so:
<div id="mpTracks">
"undefined"
<div id="song0">...</div>
<div id="song1">...</div>
</div>
Googling this problem yielded alot of related problems but that didn't help me.
Does anyone know what the problem might be?
Initialize your variable to an empty string, before using it:
var songsStructure = '';
You did not set an initial value, so it is set to undefined. According to JS rules for concatination, this undefinedis then concatenated with the strings generated by the for loop leading to your result.
You have to initialize the songsStructure variable.
Write
function loadFromPlaylist(playlist) {
var songsStructure="";
and your problem will be solved.

Categories