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/
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);
});
var modulesDemo = ['module1', 'module2'];
var moduleHtml='', pdfContent='';
$.each(modulesDemo, function( index, module ) {
if(typeof window[module] === 'function'){
window[module](function(content){
moduleHtml +=content;
if(modulesDemo.length==index+1){
pdfContent += '<table>';
pdfContent += moduleHtml;
pdfContent += '</table>';
console.log(pdfContent);
}
});
}
});
function module1(callback){
var content='';
var canvas = $("#demoCanvas")[0];
var img = canvas.toDataURL("image/png");
content += '<tr>';
content += '<td>';
content += '<img style="width:100%;height:100%;margin-top:20px !important" src="'+img+'" />';
content += '</td>';
content += '</tr>';
callback(content);
}
function module2(callback){
function module2(callback){
var img;
var content;
html2canvas($("#demoCanvas1"), {
onrendered: function(canvas) {
img = canvas.toDataURL("image/png");
content += '<tr>';
content += '<td>';
content += '<img style="width:100%;height:100%;margin-top:20px !important" src="'+img+'" />';
content += '<td>';
content += '</tr>';
//alert(2);
callback(content);
}
});
}
}
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='demoCanvas'></canvas>
<!-- end snippet -->
when i am using callback in $.each then loop is not working synchronous.Iterate doesn't wait for function complete.Can anyone help me.
Every effort will be appreciated
Thanks!
You have defined the functions as module1 and module2 but in modulesDemo array you are putting names as:
var modulesDemo = ["module_1","module_2"];
These names are different than the actual function names (notice the underscores?). So your functions are not getting called.
Edit:
Based on your comment, your issue can not be reproduced. See the code snippet below.
var modulesDemo = ['module1', 'module2'];
var moduleHtml='', pdfContent='';
$.each(modulesDemo, function( index, module ) {
if(typeof window[module] === 'function'){
window[module](function(content){
moduleHtml +=content;
if(modulesDemo.length==index+1){
pdfContent += '<table>';
pdfContent += moduleHtml;
pdfContent += '</table>';
//$scope.exportDashboardProcess(pdfContent,layout,size);
console.log(pdfContent);
}
});
}
});
function module1(callback){
var content='';
var canvas = $("#demoCanvas")[0];
var img = canvas.toDataURL("image/png");
content += '<tr>';
content += '<td>';
content += '<img style="width:100%;height:100%;margin-top:20px !important" src="'+img+'" />';
content += '</td>';
content += '</tr>';
callback(content);
}
function module2(callback){
var content='';
var canvas = $("#demoCanvas")[0];
var img = canvas.toDataURL("image/png");
content += '<tr>';
content += '<td>';
content += '<img style="width:100%;height:100%;margin-top:20px !important" src="'+img+'" />';
content += '</td>';
content += '</tr>';
callback(content);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id='demoCanvas'></canvas>
I am a beginner in javascript. I have researched the forum for answers to my question. there were a couple that I think I could have used except with my code I am, not sure where or how to put it. Can someone help me? I need to show the eight rows right aligned. Thank you !!!
results.each(function(index) {
var result = "";
var theseClmStats = record.tables.PlanClmStats[index].tables.ClmStats;
var thisPlanClmStats = record.tables.PlanClmStats[index];
//query("#test").append(thisPlanClmStats.fields["PlanName"]+ " (" + index + ') has ' + thisPlanClmStats.tables.length +' table(s)<br/>');
if(thisPlanClmStats.fields.PlanId != null) {
theseClaimSource = thisPlanClmStats.tables.ClmStats.ClaimSource;
result += '<tr data-repeat="" data-breakable="ClaimSource' + index +'">';
result += '</tr>';
var ClmStatslen = theseClmStats.length;
for (var i=0; i < ClmStatslen; i++) {
var thisClmStats = theseClmStats[i];
result += '<tr data-repeat="" data-breakable="ClmStats' + i +'">';
result += '<td><br/></td>';
result += '<td class="data PlanID" textAlign:right>'+ thisClmStats.fields["ClaimSource"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["UniqueParticipants4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["ClaimVolume4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["ClaimAverage4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["PercentageofTOTALVolume4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["Paid4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["Pending4"] + '</td>';
result += '<td class="data PlanID">'+ thisClmStats.fields["Denied4"] + '</td>';
result += '</tr>';
}
}
this.after(result);
});
You seem to be mixing a bunch of concepts together. To make the text right-align in a table cell (<td>), you could just apply CSS to one of the classes you are using, such as:
<style type="text/css">
td.PlanID {text-align:right}
</style>
Then, when you append the HTML, the CSS will automatically be applied.
If you can't adjust the CSS file (or HTML file), then try adding to your JS:
document.getElementsByClassName("PlanID").style.textAlign= "right";
You would then add this line at the end of your Javascript. But it probably is better (and cleaner) to use the CSS method.
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) );
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