I have list of restaurants and I have to append pictures of each restaurant, which is coming from a database. For this I made div's id dynamic but the pictures not append on that div. If I make the div's id static then it shows the picture coming from the server. The problem is with making the div id dynamic. Please help me. Here is my sample code:
$("#list").empty();
$.each(data, function (i, item) {
if (data[i].has_logo == 1) {
$('#pic' + i).css("background-image", "url('http://www.thefoodhive.com/web_root/provider_uploads/" + data[i].id + "/logo.jpg')");
}
if (data[i].has_menu == 0) {
status = 'Call Now';
} else {
status = 'Order Now';
}
if (data[i].from_time == '' || data[i].from_time == null) {
data[i].from_time = 'NA';
data[i].to_time = '';
}
content = '<div ><div class="container"><div id="pic' + i + '" class="left"></div><div class="right"><div class="rightno">' + data[i].name + '</div></h4></p><i>Address:' + data[i].address + ',Timing:' + data[i].from_time + '-' + data[i].to_time + '</i><br><center><div style="float: right;"></div></div> <div class="bottom"><div class="btnleft" style="float: left;"><input class="callbttn" value="CALL NOW"type="button"></input></div><div class="btnright" style="float: left;"><input class="callbttn" value="' + status + '" type="button" onclick="getdata(\'' + data[i].id + '\',\'' + data[i].has_menu + '\',\'' + data[i].phone_no + '\');"></input></div></div>';
You are applying style to a div that doesn't exists yet...
Try to apply the background inline, like this:
content = '<div ><div class="container"><div id="pic' + i + '"
class="left" style="background-image:url(http://www.thefoodhive.com/web_root/provider_uploads/' + data[i].id + '/logo.jpg">...
Related
I have a page in which I have to show list of data in UI through ajax & append the list data in html table save that list data into Local Storage with Jquery, My question is that I want to implement lazy load in UI such that user clicks a button (Click to view more list), and after clicking the button the ajax calls another list with limit & offset to show more list & append the new list below the existing list in UI and also save the data into local storage along with the existing data present.
My Ajax Call for List Data
var sendingData = {
limit: "50000",
offset: "0"
};
$.ajax({
type: 'POST',
url: "/Common/Item/getselleritems?SellerId=" + userid,
data: sendingData ,
crossDomain: true,
success: function (data)
{
localStorage.setItem("productCode", JSON.stringify(data));
},
error()
{
//Do something
}
});
``
My Html design Function
function showProducts()
{
var productsStorage = localStorage.getItem("productCode");
var products = JSON.parse(productsStorage);
var trHTML = '';
$("table tbody").html("");
$.each(products.Data, function (key, value)
{
trHTML += '<tr>'
+ '<td class="d-md-flex align-items-center">' + '<figure style="' + imgStyle + '"><a href="" title="Photo title" data-effect="mfp-zoom-in">' +
'<img src="' + imgSrc + '" alt="thumb" class="lazy"></a></figure>' +
'<div class="flex-md-column">' +
'<h4 class="package_name" id="itemdescription_' + value.Id + '" onclick = "packageDetails(\'' + value.Price + '\',\'' + value.Name + '\',\'' + value.Description
+ '\',\'' + itemTimeSlotType + '\',\'' + value.ServiceName + '\',\'' + value.PreparationTime + '\',\'' + value.Quantity + '\')" >' +
'<i class="icon_box-selected" style="' + style + '; margin-right:3px"></i>' +
value.Name + '</h4>' +
'<p>' + value.Description + '</p>' +
'<em>' + "Available In: " + itemTimeSlotType + '</em>' + '<br>' +
'<span class="stars_sellerItem" style="' + starStyle + '">' + value.FoodtestAvgRating + ' <i class="icon_star"> </i> ' +
'</span>' +
'</div>' +
'</td>' + '<td style="padding: 0.75rem 0 0.75rem 0;">' +
'<strong id="itemprice_' + value.Id + '">' +
'<i class="fa fa-inr" aria-hidden="true"></i>' + value.Price +
'</strong>' +
'</td>' +
'<td class="options">' +
'<div class="dropdown dropdown-options">' +
'<i class="icon_plus_alt2"></i>' +
'<div class="numbers-row number" id="item2_' + value.Id + '" data-id="' + value.Id + '">' +
'<input type="text" value="1" class="form-control" name="quantity" id="itemvalue_' + value.Id + '" onchange="getval(' + itemId + ');" readonly>' +
'<div class="inc button_inc plus">' + '+' + '</div><div class="dec button_inc minus">' + '-' + '</div>' + '</div>' +
'</td>' + '</tr>';
}
$("table tbody").append(trHTML);
}
I would like to select the content of this element
<div class="entry-content">
comment.body +
</div>
I want to get that comment.body in the function I call below, more precisely in
var body = parent.find('entry-content');
How can I select the content of a certain div? I tried val() and contents() and none of them worked.
Any suggestion?
$("body").on("click", ".show-textarea", function(){
var answerid = $(this).data('answer');
var type = $(this).data('type');
var questionid = $(this).data('question');
var $commentForm = $(this).parent().find('.comment-form').first();
console.log(answerid);
$.getJSON("/controller/api/comments/comment.php", {
answerid : answerid,
questionid : questionid,
type : type
}, function (data) {
$commentForm.find('article').remove();
console.log("AID " + answerid);
console.log("Data" + data.length);
$.each(data, function(i, comment) {
console.log("Comment:" + comment);
$commentForm.append('<article class="tweet-data">' +
'<div class="comment-items">' +
'<div class="qa-c-list-item hentry comment" id="c3574">' +
'<div class="asker-avatar">' +
'<a>' +
'<img width="40" height="40" src="' +
comment.user_photo +
'"></a>' +
'</div>' +
'<div class="qa-c-wrap">' +
'<div class="post-button">' +
'<button name="" onclick="" class="btn icon-flag" title="Flag this comment as spam or inappropriate" type="submit">flag</button>' +
'<button name="" class="btn icon-answers" title="Reply to this comment" type="submit">reply</button>' +
'</div>' +
'<span class="qa-c-item-meta">' +
'commented' +
' 1 day' +
' ago' +
' by ' +
'<a style="display: inline" href="" class="qa-user-link url nickname">' +
comment.username +
'</a> ' +
'<span class="qa-c-item-who-points"> ' +
'<span class="qa-c-item-who-points-pad">(</span><span class="qa-c-item-who-points-data">140</span><span class="qa-c-item-who-points-pad"> points)</span> ' +
'</span> ' +
'</span> ' +
'</span> ' +
'<div class="qa-c-item-content" style="color: #2d2727; font-size: 13px"> ' +
'<a name="3574"></a>' +
'<div class="entry-content">' +
comment.body +
'</div> ' +
'</div> ' +
'<div class="comment-edit-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<button class = "edit-comment btn {if !$isMine}hidden{/if}" type="button">Edit</button>' +
'</form>' +
'</div> ' +
'</div> <!-- END qa-c-item --> ' +
'</div>' +
'</div></article>');
});
});
$commentForm.show();
});
$("body").on("click", ".textarea-ok, .textarea-cancel", function(){
commentsFetched = false;
$('.comment-form').hide();
});
$("body").on("click", ".edit-comment", function(){
console.log("Hello");
var parent = $("body").find('article').last();
var body = parent.find('entry-content');
console.log(body);
var parent_parent = $("body").find('article').parent().last();
parent.remove();
console.log(parent);
var button = $(this),
commentField = $('<div class="comment-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<textarea name="comment" rows="4" cols="40" class="qa-form-tall-text">' +
body +
'</textarea>' +
'<input type="hidden" name="answerid" value="" />' +
'<input type="hidden" name="questionid" value="" />' +
'<button type="submit" class="textarea-ok">Edit Comment</button>' +
'</form>' +
'</div>'); // create a textarea element
commentField
// set the textarea's value to be the saved content, or a default if there is no saved content
.val(button.data('textContent') || 'This is my comment field\'s text')
// set up a keypress handler on the textarea
.keypress(function(e) {
if (e.which === 13) { // if it's the enter button
e.preventDefault(); // ignore the line break
button.data('textContent', this.value); // save the content to the button
$(this).remove(); // remove the textarea
}
}).appendTo(parent_parent); // add the textarea to the document
});
Since the binding is on '.edit-comment' which is a child of the '.tweet-data' encapsulating each individual entry (from the looks of your logic) I would suggest doing
$(this).closest('.tweet-data').find('.entry-content').text();
Your current logic is going to the last article for the 'parent' element. So if you tried to click the edit comment option on a tweet data other than the last one, your logic will most likely not work. Doing the lookup contextually by which element was clicked will fix this potential issue.
I have a problem with my code. I am pushing items into a new array and displaying two of them in a DIV. For some reason its showing the same item twice rather than showing two separate items. Hoping someone can help me out with this. I just need a way to prevent the same recipe from being able to show twice in the DIV.
var categoryItems = [];
var recipeTitle = $('#recipeTitle').text();
$.each(recipe_data, function(i, item){
if (item.recipeCategory == "4" && recipeTitle !== item.recipeName) { categoryItems.push(item); }
});
var similarRecipe = '';
var randomRecipe = {};
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit: Please take a look at this fiddle for an example. It should not show the same recipe twice when refreshing, rather show two different recipes from the category. My problem is that is is sometimes it is showing the same one twice when you refresh. https://jsfiddle.net/wn4fmm5r/
you are generating one random Recipe and displaying same twice into your for loop
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
try including your statement for generating random recipe inside loop.
for(var i = 0; i < categoryItems.length; i += 2) {
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit for no repeating ----
var counter;
for (var i = 0; i < categoryItems.length; i += 2) {
var item = Math.floor(Math.random() * categoryItems.length);
if (!counter) {
counter = item;
} else {
if (counter == item) {
item = Math.floor(Math.random() * categoryItems.length);
counter = item;
}
}
randomRecipe = categoryItems[item];
similarRecipe = ['<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL + '" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>'];
$('#recipeSimilar').append(similarRecipe);
}
I have a dynamic html elements that renders in a for loop the dynamic parent element has a dynamic id, how can I hide the dynamic elements or the container and its content if the id which is dynamic has a value lets say "Product".
Thank you in advance.
This is the dynamic elements that i rendered using for loop
for (var i = 0; i < a_data.products.length; i++) {
produst_list += '<a href="#" class="plLinkToFull" data-sn="' + a_data.products[i].serial + '" id="' + a_data.products[i].productName + '">';
produst_list += '<div class="plProductContainer">';
produst_list += ' <div class="plProductBTN">';
//produst_list += ' <div class="plProductThumb pull-left ' + (a_data.products[i].pid === 'TE80'?'apMaximumPanelTi8':'apMaximumPanel') + '"></div>';
produst_list += ' <div class="plProductThumb pull-left ' + getPanelClsss(a_data.products[i].pid) + '"></div>';
produst_list += ' <div class="plProductLeft">';
produst_list += ' <h6 style="margin-bottom: -5px;">' + a_data.products[i].productName + '</h6>';
produst_list += ' <div class="plLowerStatusSN"><span>' + a_data.products[i].serial + '</span></div>';
produst_list += ' </div><div class="plLowerStatus">';
produst_list += ' <div class="' + ((a_data.products[i].remainingDays > 0) ? "plIconGreen" : "plIconRed") + '">';
produst_list += ' <span class="glyphicon glyphicon-time" style=""> </span></div>';
produst_list += ' <span class="' + ((a_data.products[i].remainingDays > 0) ? "plExpiryOK" : "plExpiredDate") + '">Expire: <strong>' + a_data.products[i].expirationDate + '</strong></span>';
produst_list += ' </div></div></div></a>';
}
With filter :
$('a.plLinkToFull').filter(function(){
return this.id.contains("product");
}).hide();
You can make like this:
$('.plLinkToFull').prev('id') = i;
or
$('.plLinkToFull').attr("id", i);
The i have to send to new Method, for saving the loop.
try this:
var id = 'Product';
$('a[id*="'+id+'"]').hide();
if you want to hide it by clicking use event delegation
var el = 'a[id*="'+id+'"]';
$('body').on('click',el,function(){
$(this).hide();
});
I am working on preparing some dynamic html with jquery and json object. but the problem is that when my json object has around 1500 rows it takes ages to load.
is there a way to load the thing faster.
Some code.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
innerList1 += '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>';
}
else if (type = "exportall") {
innerList2 += CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat);
}
controlId++;
}));
$("#itemList").html(innerlist1);
EDIT : createliwithspan method
function CreateLiWithSpans(id, html, isLeft, isAddAll, scaleID, scaleType, hasWeights, customColumnType, valueFormat, newText) {
var ancClass = isLeft ? 'actionRight' : 'actionLeft';
var liObject = "";
if (newText == null) {
newText = "";
}
if (isLeft) {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><span style="margin:0 10px 0 20px;pagging:0"><input title = "' + (newText == "" ? html : newText) + '" type="text" id="' + id + 'displayText" value="' + (newText == "" ? html : newText) + '" /><span style="color:Red; width:100%;" id="' + id + 'displayTextError"></span></span><span style="float:left">' + CreateDropDown('ddl_' + id, valueFormat, hasWeights) + '</span><a class="' + ancClass + '"></a></li>';
}
else {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><a class="' + ancClass + '"></a></li>';
}
return liObject;
}
You can use for loop instead of jQuery.each, that will be faster. Store the itemCount before the loop, and use that:
itemCount = jsonData.items.length;
for(var i = 0; i < itemCount; i++ ) {
...
You can also use use an array instead of string concatenation, like so:
var innerList = [];
... // inside the loop
innerList.push(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
... // after the loop
$("#itemList").html(innerList.join(''));
This will be faster in IE, I'm not sure about other js engines.
These two methods will not make a significant difference, so you should try implementing a client side pagination from json. (Not by hiding and showing divs, by rendering only visible page into the DOM).
Instead of waiting for the loop to end to append your data, why not actively append the data as you process it. This will allow the user to get immediate feedback instead of waiting for the whole thing to process. Other than this, I'd stick with my original comment to page the data.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
$("#itemList").append( '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>');
}
else if (type = "exportall") {
$("#itemList2").append(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
}
controlId++;
}));
Try replacing jQuery.each with a plain old for...in loop. Using jQuery.each adds overhead that you don't need.
Don't concatenate strings inside your loop. Instead, .push them onto an array variable and use .join('') to build the string all at once at the end.
You may need to eliminate CreateLiWithSpans as a separate function in order to fully implement (2).
Changing from using jQuery.each to a standard javascript for loop should speed it up a bit. Make sure that you save the length to a variable like this though:
for(var i = 0, len = jsonObject.AvailableColumns.length; i < len; i++){
var l = jsonObject.AvailableColumns[i];
// Continue with rest of code
}
Probably won't be a huge increase but every little helps.
Also try lowering the number of function calls you make as these have added overhead (not usually an issue, but in a large loop it can help). Unless the code is shared between functions try doing it inline and see how much that speeds it up.