Parse Json value to html tag - javascript

How can i parse each tag of k and v to html tag.
var json = $.parseJSON(data);
var x = 0;
$(json).each(function(i, val) {
$.each(val, function(k, v) {
var my_href = "#";
var img_source = "..img";
var my_title = "...abcd";
var slider_index = "wows_" + x;
x++; //increment link id
$('#ws_images').html('<li><img src="' + img_source + '" alt="" title="' + my_title + '" id="' + slider_index + '" /></li>');
});
});
The json is as follows:
[
{
"news_id":"8",
"title":"ddd",
"description":"ddd",
"photo":"News_images\/20020_1116863714996046_8844424307040103167_n.jpg",
"posted_on":"2015-07-12 12:54:48",
"news_type":"image_slider",
"dept_id":"1"
}
]
The value of k return the tag name but how can each tag element be parsed into the html tag.
<li><img src="' + img_source + '" alt="" title="' + my_title + '" id="' + slider_index + '" /></li>

Try utilizing single $.each() , substituting .append() for html()
var data = [{
"news_id": "8",
"title": "ddd",
"description": "ddd",
"photo": "News_images\/20020_1116863714996046_8844424307040103167_n.jpg",
"posted_on": "2015-07-12 12:54:48",
"news_type": "image_slider",
"dept_id": "1"
}];
$.each(data, function(k, v) {
$("#ws_images")
.append("<li><a href=#>"
+ "<img src=" + v. photo
+ " alt=''"
+ " title=" + v.title
+ " id=wows_" + k + " />"
+ "</a></li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul id="ws_images"></ul>

Related

jQuery When After Each Loop

I have six static html questions and then 3-4 questions being generated by JSON dynamically based upon a form choice made on a page before. What I'm trying to do is generate the questions, then create a progress bar based on the final number of questions created. Where I'm having trouble is using the jQuery when done method after my each loop. It is firing after the first iteration instead of the last. I have tried populating an array "Qs" and passing the array, after reading some other posts, but what I have hasn't worked. I would really like to segment my code and clean it up as much as possible, so I'm trying to stay away from nesting it.
var Qs = [];
var generateQs = function (){
var $dept = sessionStorage.getItem("sFGeneralDepartment1");
var $qWrapper = $("#assessmentTool");
$.getJSON("js/dept-questions.json", function(data) {
var key = $dept;
var vals = [];
switch(key) {
case 'Information technology':
vals = data.IT;
break;
case 'Finance':
vals = data.FIN;
break;
case 'Human resources':
vals = data.HR;
break;
case 'Marketing':
vals = data.MKT;
break;
default:
vals = data.OT;
break;
}
$.each(vals, function(index, value) {
var $cleanID = (value.qID).replace(/q/g, '');
$qWrapper.append('<div class="question-container rangeIcon disabled" id="' + value.qID + '"><p>Question ' + $cleanID +'</p> <h4>' + value.questionText + '</h4><ul class="answer-container"></ul></div>');
$.each(value.answers, function(i, answer) {
var $aID = answer.aID;
var $radioBtn = '<div class="radioBtn"><span class="radioBtnInner"></span></div>';
$('.question-container#' + value.qID + ' .answer-container').append('<li class="survey-item"><div class="icon-holder" id="' + $aID + '"><img src="img/' + answer.iconFileName + '" width="' + answer.iconWidth +'" height="'+ answer.iconHeight + '"/></div><input type="radio" id="'+ $aID + '" value="' + answer.pointValue + '"><label for="' + $aID + '" class="radio" data-popover="'+ answer.popoverText + '">' + $radioBtn + '<span class="labelTopText">' + answer.labelTopText + '<span class="divider">/</span></span><span class="labelBottomText">' + answer.labelBottomText + '</span></label></li>');
});
Qs.push($cleanID);
});
console.log('done');
console.log(Qs);
});
};
$.when(generateQs($,Qs)).done(function() {
//create progress bar
console.log('starting');
var qCount = ($('.question-container').length + 1);
var qList = $('#progressBar');
for (var i = 0; i < qCount; i++){
qList.append('<li class="progress-bar-steps" data-item="q' + (i+1) + '">' + '<span class="step-text">' + (i+1) + '</span>' + '</li>');
$('.question-container').each(function (i, value){
var qId = $(this).attr('id');
if ($(this).hasClass("active")) {
$(this).css('opacity','1.0');
$('#progressBar').find("[data-item='" + qId + "']").addClass('active').html('<span class="step-text">' + (i+1) + '</span>');
$('.progress-bar-steps.active').next('.progress-bar-steps').addClass('next disabled-next').html('<span class="step-text">' + (i+2) + '</span>');
} else {
$(this).addClass('disabled');
}
});
}
});

Get title,url and image from flickr using flickr api,

I could not figure out what I am doing wrong?
Also i am having problem storing data in javascript 2d array.
Fiddle
$.getJSON(url,
function (data) {
/*Insert your titles you wanna show*/
var titles = ["box closing", "e"];
var nope = [
[],
[],
[]
];
// var len = titles.length;
var count = 0;
var col = 0;
var row=0;
$.each(data.photos.photo, function (i, item) {
var purl = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
// var pid = item.id;
var container = '<tr><td class="col-md-8"><a target="_blank" href="http://www.flickr.com/photos/' + userid + '/' + item.id + '/"><img class="span4" alt="' + item.title + '" src="' + purl + ' width=100 height=200"/></td></tr>';
var title = '<tr><td class="col-md-4" >' + item.title + '</td></tr>';
nope[row][0] = item.title;
nope[row][1] = container;
nope[row][2]=title;
/*Show only image with in titles*/
if (item.title == titles[count]) {
$(container).appendTo('#contain');
$(title).appendTo('#contain');
//$("a.imageurl").append(" ");
//$("#name").append(title);
//$("a.imageurl").append(purl);
//$("a.imageurl").append(" ");
//purl = '
$("#demo").append(nope[row][col]);
$("#demo").append(nope[row][col]);
$("#demo").append(nope[row][col]);
}
col++;
count = count + 1;
});
});

Move Table Rows

I have my table like this, I want to move up and down these rows on click these arrows can anybody help me out ......
function MoveRowDown(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertAfter(rows.eq(index + 1));
}
function MoveRowUp(tableId, index)
{
var rows = $("#" + tableId + " tr");
rows.eq(index).insertBefore(rows.eq(index - 1));
}
int ItemSetupID = EBusiness.GetCommonSetupID(this.Data.WFID, EBusiness.CommonSetupID.ItemSetup);
MModules objItemSetupModules = new MModules();
objItemSetupModules.LoadModules(ItemSetupID);
StringBuilder ret = new StringBuilder(4000);
ret.Append("<table class=\"box-table-a\"><tr><td><img id=\"left\" src=\"../../images/downarrow.png\" onclick=\"MoveRowDown(tableId,index);\"></td></tr><tr><td>");
ret.Append("<table id=\"tableId\" class=\"box-table-a\"><tr><th>Items</th></tr>");
int index = 0;
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr><td><input type=\"hidden\" name=\"Items" + module.ModuleID + "\" id=\"Items" + module.ModuleID + "\" />");
ret.Append("<tr><td><input type=\"hidden\" name=\"index" + index + "\" id=\"index" + index + "\" />");
ret.Append("<a href=\"#\" class=\"lnkShowFilter\" onclick=\"$('#index" + index + "').val('#index" + index + "'); $('.lnkShowFilter').css('color', '#000000');this.style.color='#FF0000';ShowFilterSaleMargin('" + module.TableName + "', '" + module.Title + "', 'divFilter" + module.ModuleID + "')\">");
ret.Append("" + module.Title + "</a> ");
ret.Append("<input type=\"hidden\" id=\"hidShowFilter" + module.Title + "\" value=\"false\" />");
ret.Append("<div id=\"divFilter" + module.ModuleID + "\" style=\"text-align:left;border:1px SOLID #333333;background-color:White;display:none;position:absolute;\">");
ret.Append("<div id=\"sdivFilter" + module.ModuleID + "\" style=\"border:1px SOLID #EEEEEE;background-color:#AAAABB; width:150px;height:100px;overflow-y:auto;\"></div>");
ret.Append("<input type=\"button\" value=\" OK \" class=\"button\" onclick=\"$('#' + openedDivID).hide();GetItemData('" + module.ModuleID + "', '" + module.Title + "');\" />");
ret.Append("</div></td></tr>");
index++;
}
ret.Append("</table></td><td>");
ret.Append("<table class=\"box-table-a\"><tr><th>Data</th></tr>");
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr id=\"tdModule" + module.ModuleID + "\"><td ></td></tr>");
}
ret.Append("</table></td></tr><tr><td><img id=\"left\" src=\"../../images/uparrow.png\" onclick=\"MoveRowUp(tableId, index);\"></td></tr></table>");
this.Output = ret.ToString();
We have to use insertBefore and insertAfter methods of jQuery to insert before and after the dom element respectively.
The sample code is like:
if(e.target.innerHTML == "Up") {
if(index != 0) {
currRow.insertBefore($("tr:eq(" + (index-1) + ")"));
}
} else if(e.target.innerHTML == "Down") {
if(index != (totalTrs-1)) {
currRow.insertAfter($("tr:eq(" + (index+1) + ")"));
}
}
Working DEMO
Source:
Insert After jQuery
Insert Before jQuery
JavaScript-Move Up and Down HTML Table Row: Working Code
function MoveRowDown(tableId)
{
var index=parseInt(document.getElementById("HiddRowindex").value);
var rows = $("#" + tableId + " tr");
table= document.getElementById(tableId);
rowCount = table.rows.length;
if(index+1<rowCount)
{
rows.eq(parseInt(index)).insertAfter(rows.eq(index + 1));
index=(index+1);
document.getElementById("HiddRowindex").value=index;
}
}
function MoveRowUp(tableId)
{
var index=parseInt(document.getElementById("HiddRowindex").value);
var rows = $("#" + tableId + " tr");
table= document.getElementById(tableId);
rowCount = table.rows.length;
if(index-1>0)
{
rows.eq(index).insertBefore(rows.eq(index - 1));
index=(index-1);
document.getElementById("HiddRowindex").value=index;
}
}
///////////////////////////End JavaScript///////////////////////////////
///////////////////////////Code////////////////////////////////////////
int ItemSetupID = EBusiness.GetCommonSetupID(this.Data.WFID,
EBusiness.CommonSetupID.ItemSetup);
MModules objItemSetupModules = new MModules();
objItemSetupModules.LoadModules(ItemSetupID);
StringBuilder ret = new StringBuilder(4000);
ret.Append("<table class=\"box-table-a\"><tr><td><img id=\"left\" src=\"../../images/downarrow.png\" onclick=\"MoveRowDown('tableId');\"></td></tr><tr><td>");
ret.Append("<table id=\"tableId\" class=\"box-table-a\"><tr><th>Items</th><th>Data</th></tr><input type=\"hidden\" name=\"HiddRowindex\" id=\"HiddRowindex\" value=\"\" />");
int index = 1;
foreach (MModule module in objItemSetupModules.Modules)
{
ret.Append("<tr><td><input type=\"hidden\" name=\"Items" + module.ModuleID + "\" id=\"Items" + module.ModuleID + "\" />");
ret.Append("<a href=\"#\" class=\"lnkShowFilter\" onclick=\"$('#HiddRowindex').val($(this).closest('td').parent()[0].sectionRowIndex); $('.lnkShowFilter').css('color', '#000000');this.style.color='#FF0000';ShowFilterSaleMargin('" + module.TableName + "', '" + module.Title + "', 'divFilter" + module.ModuleID + "')\">");
ret.Append("" + module.Title + "</a> ");
ret.Append("<input type=\"hidden\" id=\"hidShowFilter" + module.Title + "\" value=\"false\" />");
ret.Append("<div id=\"divFilter" + module.ModuleID + "\" style=\"text-align:left;border:1px SOLID #333333;background-color:White;display:none;position:absolute;\">");
ret.Append("<div id=\"sdivFilter" + module.ModuleID + "\" style=\"border:1px SOLID #EEEEEE;background-color:#AAAABB; width:150px;height:100px;overflow-y:auto;\"></div>");
ret.Append("<input type=\"button\" value=\" OK \" class=\"button\" onclick=\"$('#' + openedDivID).hide();GetItemData('" + module.ModuleID + "', '" + module.Title + "');\" />");
ret.Append("</div></td>");
ret.Append("<td id=\"tdModule" + module.ModuleID + "\"></td>");
ret.Append("</tr>");
index++;
}
ret.Append("</table></td>");
ret.Append("</tr><tr><td><img id=\"left\" src=\"../../images/uparrow.png\" onclick=\"MoveRowUp('tableId');\"></td></tr></table>");
this.Output = ret.ToString();

Javascript SHIFT and POP on Associative Array

Using a regular array I am able to grab the image src from an array using shift() and pop(); I would like to do the same thing using an associative array to add a name and id.
Single Array
var products = ['product1.jpg'];
$('#products').append('<img src="' + products.shift() + '">');
Associative Array
var products = [{id:'1',name:'product 1',image:'product1.jpg'}];
$('#products').append('<img id="' + products.shift() + '" name="' + products.shift() + '" src="' + products.shift() + '">');
You're using a regular array full of objects, so shift and pop will work, but return you the object.
var products = [{id:'1',name:'product 1',image:'product1.jpg'}];
var prod = products.shift();
$('#products').append('<img id="' + prod.id + '" name="' + prod.name + '" src="' + prod.image + '">');
This line: var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; declares an array with a single value inside. The single value is an object with the properties id, name, and image. When you call shift on the array, the value returned will be this object.
var products = [{id:'1',name:'product 1',image:'product1.jpg'}];
for(var i =0; i < products.length; i++){
var product = products[i];
$('#products').append('<img id="' + product.id + '" name="' + product.name + '" src="' + product.image + '">');
}
shift() is going to pull the whole object out of the index, not piece by piece like in your example.
You would need to access the object by name to get what you want.
var products = [{id:'1',name:'product 1',image:'product1.jpg'}, {id:'2',name:'product 2',image:'product2.jpg'}];
var currentProduct = products.shift();
$('#products').append('<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">');
to loop through it
while(products.length>0){
var currentProduct = products.shift();
$('#products').append('<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">');
}
better performance loop would be one write to the DOM
var strOut = "";
while(products.length>0){
var currentProduct = products.shift();
strOut += '<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">';
}
$('#products').append( strOut );
You can cache the shift, and use the object's properties:
var products = [{id:'1',name:'product 1',image:'product1.jpg'}];
var product = products.shift();
$('#products').append('<img id="' + product.id
+ '" name="' + product.name
+ '" src="' + product.image + '">');
You can store the values differently, as a multi-dimensional array:
var products = [['1','product 1','product1.jpg']];
var product = products.shift();
$('#products').append('<img id="' + product.shift()
+ '" name="' + product.shift()
+ '" src="' + product.shift() + '">');

Creating dynamic html with json taking too much time

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.

Categories

Resources