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() + '">');
Related
Really new to JS and wondering if someone knew how i can change the following into using jQuery each:
current:
for (var i in basket){
var item = basket[i];
var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>£" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
$(".basket-content").append(row);
}
attempted:
$.each(function(i, basket){
for (var i in basket){
var item = basket[i];
var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>£" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
$(".basket-content").append(row);
}
});
The first argument to $.each is the array/object you want to iterate over. The arguments to the function are the index and the element (so you don't need to assign item yourself).
$.each(basket, function(i, item) {
var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>£" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
$(".basket-content").append(row);
});
here is an example to make a array loop in jquery
var array = new Array();
array.push('test');
array.push('test2');
$.each(array, function(i, basket){
console.log('key', i);
console.log('value', basket);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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>
Annoyingly, the FlickrAPI provides the title and description of a photo in two separate methods. I'm having trouble getting the description of an image from Flickr and was wondering if you could highlight the error in my script.
for (var i = 0; i < photos.photo.length; i++) {
var descPhoto = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key="+API_KEY+"&photo_id="+photos.photo[i].id+"&format=json&nojsoncallback=1";
var descArr = [];
$.getJSON(descPhoto, function(data) {
var value = data.photo.description._content;
descArr.push(value);
});
link = 'https://farm' + photos.photo[i].farm + '.static.flickr.com/' + photos.photo[i].server + '/' + photos.photo[i].id + '_' + photos.photo[i].secret + '_';
title = this._htmlEscape( photos.photo[i].title );
var lightbox = "lightbox";
listItems +=
'<li ' + 'class="' + liClassNoDots + '">' +
'<a href="' + link + self.options.imageSize + '.jpg" title="' + title + '" class="' + aClassNoDots + '" target="_blank" data-lightbox="' + lightbox + '">' +
<img alt="' + title + '" src="' + link + self.options.thumbnailSize +'.jpg"/>' +
'<div class="hover-box">' +
'<p>' + descArr[i] + '</p>' +
'<button class="box-button view">View larger</button>' +
'<button class="box-button request">Request</button>' +
'</div>';
'</a>' +
'</li>';
}
Getting the title is fine and I've checked by API string calls and they work in the address bar of my browser.
I've used console.log() and the array is printed out correctly and I'm getting the descriptions. However, in each <p> tag the script is returning undefined in each instance.
However, if I run the script through the debugger the parapgraph tags are populated with the descriptions. Can somebody help?!
i think the problem is in following code::
..
$.getJSON(description, function(desc) {
value = desc.photo[ i ].description._content;
});
the service url returns photo object whereas you are using photo array, change to:
..
$.getJSON(description, function(desc) {
value = desc.photo.description._content;
console.log( value );
});
I'm having problems with dynamically adding a row to a table using data stored in two arrays (categories and treatments). The arrays are fine, I've determined that.
When passing just the categories array the new row displays but the select box reads [object:object], it's clearly blank.
When I pass a second array with it, as shown below, the console reads 'undefined is not a function'.
Any help would be hugely appreciated!
// Add an extra row when button is clicked
var counter = 1;
$('input.add').click(categories, treatments, function(){
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
$.each(categories, function(key, value) {
$('#category' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
$.each(treatments, function(key, value) {
$('#treatment' + counter)
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
});
The first parameter for the jQuery .click() is an Object, and you're trying to pass two arrays.
This should work for you (remember to check for the missing semi-colons):
// Create an Object obj containing the two arrays.
$('input.add').click(obj = { categories: categories, treatments: treatments }, function () {
counter++;
var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';
// Use the obj.
$.each(obj.categories, function (key, value) {
$('#category' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';
// Use the obj.
$.each(obj.treatments, function (key, value) {
$('#treatment' + counter);
newRow += '<option value ="' + key + '">' + value + '</option>';
});
newRow += '</select></td></tr>';
$('table.treatments').append(newRow);
});
Demo
jQuery .click()
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.