Trying to print my htmlString in the .listing div but I'm only getting the last item in the array, yet the console.log loops correctly. what gives?
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').html(htmlString);
}); //end each
You are overriding the contents of listing in each iteration, instead you need to append the contents.
When you use .html() it will remove the current contents of the element, then replace it with the passed content. To add the new content after the existing one you can use .append()
If you want to clear the listing element, you can do it before the beginning of the loop as shown below
$('.listing').html(''); //clear the listing element if needed
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>';
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').append(htmlString); //add the current content to existing one
}); //end each
With .html() you're replacing the contents after each loop. Instead, append:
$('.listing').html(htmlString);
becomes:
$('.listing').append( $(htmlString) );
Related
I would like to add a jquery toggle effect on my code which has HTML within my Javascript. Any advice?
GuessGame.prototype.createBoard = function(){
var html = '';
Object.keys(this.cards).forEach(function(key) {
html += '<div class="card" id="' + key + '"';
html += ` style='background-image: url(img/${key}.jpg)'`;
html += '>'
html += '<div class="front" ';
html += 'id="' + key + '">';
html += '</div>';
html += '</div>';
});
// Add all the divs to the HTML
document.getElementById('board').innerHTML = html;
In your example you're not really using the power of jQuery.
Here is a better approach.
GuessGame.prototype.createBoard = function(){
var board = $('#board');
Object.keys(this.cards).forEach(function(key) {
var card = $('<div class="card" id="' + key + '" style="background-image: url(img/${key}.jpg)"><div class="front"></div></div>');
// add onClick Event
card.on('click', function(e) {
card.toggleClass('toggled-class');
});
// append card to board
board.append(card);
});
i have a results object that include some data like Creation_date, approval_date,.... . i put the results in loop in javascript and create nested div. but when i debug it , those div aren't nested,unfortunately each one closed after created.
any help?
var Item=document.getElementById('myItems');
Item.innerHTML="";
for(var i=0;i<myItem.results.length;i++){
Item.innerHTML +='<div class="row">';
Item.innerHTML +='<div class="col-md-12">';
Item.innerHTML +='<img src="'+myItem.results[i].images+'"/>';
Item.innerHTML +='</div>';
Item.innerHTML +='</div>';
Item.innerHTML +='<div class="row">';
Item.innerHTML +='<div class="col-md-4">';
Item.innerHTML +='Created on:'+myItem.results[i].creation_date;
Item.innerHTML +='</div>';
Item.innerHTML +='<div class="col-md-4">';
Item.innerHTML +='incident_date:'+myItem.results[i].item_date;
Item.innerHTML +='</div>';
Item.innerHTML += '<div class="col-md-4">';
Item.innerHTML +='approval_date:'+myItem.results[i].approved_date;
Item.innerHTML +='</div>';
Item.innerHTML +='</div>';
}
You're assigning to .innerHTML. Every time you do that, the dom is rebuild. JS and the DOM engine have no idea you're going to be adding more stuff again, so it tries to rebuild the DOM tree with VALID html, fixing any errors you introduced with the one line added.
e.g.
item.innerHTML = '<div>';
actually produces <div></div> in the tree, because you're not allowed to build an invalid tree.
Don't do repeated innerHTML assignment. Build your html in a string, then assign the string ONCE
e.g.
foo = '<div>';
foo += 'hi mom!';
foo += '</div>';
Item.innerHTML += foo;
Not only does this let you build up your html properly, it's also more efficient, and only rebuilds the tree ONCE, instead of each time you modified innerhtml.
Put all html in buffer and insert it after for loop.
Since you are directly assigning innerHTML DOM is contineuosly re-building in for loop.
var Item = document.getElementById('myItems');
var buffer = '';
for (var i = 0; i < myItem.results.length; i++) {
buffer += '<div class="row">';
buffer += '<div class="col-md-12">';
buffer += '<img src="' + myItem.results[i].images + '"/>';
buffer += '</div>';
buffer += '</div>';
buffer += '<div class="row">';
buffer += '<div class="col-md-4">';
buffer += 'Created on:' + myItem.results[i].creation_date;
buffer += '</div>';
buffer += '<div class="col-md-4">';
buffer += 'incident_date:' + myItem.results[i].item_date;
buffer += '</div>';
buffer += '<div class="col-md-4">';
buffer += 'approval_date:' + myItem.results[i].approved_date;
buffer += '</div>';
buffer += '</div>';
}
Item.innerHTML = buffer;
I don't see why you just don't use jQuery .append() http://api.jquery.com/append/
So I have this jquery function that is pulling data from another domain and i want to display that data with ajax when the user enters a value into the search box. As of now the app continuously gives me the error message I wrote from the error state no matter if I search by .productName or .itemCode. Any ideas what I'm doing wrong?
function foodQuery() {
var key = "123456789";
$("#searchinput").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
$(".listing").html("");
}
}
Since its from a different domain, you can try using jsonp
I have a function to generate data-content for bootstrap popover from Json .
The problem with the function is that, if I pass json object in which a member contains a single quote then the popover content is not set.
function setupopoverContent(content) {
var json = JSON.parse(content);
var contents = '<div style="">'
contents += '<div id="hellobar" class="large right remains_at_top row-fluid" style="background-color: ' + json.BarColor + '; color: ' + json.TextColor + '; border-radius: 5px;font-family: Helvetica,Arial,sans-serif;"> ';
contents += '<div id="hb_msg_container" class="span11"> <span id = "topbar_message" style="padding-bottom:14px;"> ';
contents += HtmlEncode(json.Message);
contents += '</span> ';
contents += '<a id = "topbar_linktext" class="hellobar_cta hb-button" href= "' + json.LinkURL + '" target="_blank" style="color: ' + json.ButtonTextColor + '; background-color: ' + json.ButtonColor + '; border-color: #000000"> ';
contents += HtmlEncode(json.LinkText);
contents += '</a></div> ';
contents += '</div></div>';
return contents;
}
Suppose that json.Message=All go'es here, then the popover content is not set.
How can i solve this problem?
Have you tried omitting HtmlEncode?
http://jsfiddle.net/z6gnpnr5/
I have the following .js code but when i test the site, it only displays the wordings as seen in each but no contents. What i want to achieve at the end is to be able to display 5 posts and also add a link at the bottom to display more mosts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">entry.title</div>';
html += '<div class="entry">author</div>';
html += '<div class="entry">publishedDate</div>';
html += '<div class="entry">contentSnippet</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
If you know that your postlist is not null, and that each entry has properties 'title', 'author', 'publishedDate' and 'contentSnippet' try this:
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
try a $.each loop on data.responseData.feed.entries, see here for details