Converting for into jQuery each - javascript

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>

Related

How can I use each loop variable (item) outside of loop

I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});

Append checkbox together with datasnapshot in a table

i want to add checkbox for each and every rows but when i try to run the code, something like this shows "[object HTMLInputElement]" instead of a checkbox
function BSIT(){
$("#stdlist").empty();
var chyear = $('#chyear').val();
$("#showtxt").html(chyear);
var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
var ref = firebase.database().ref().child("course/BSIT");
ref.orderByChild("Year").equalTo(chyear).on("child_added", function(snapshot) {
var childData = snapshot.val();
$("#stdlist").append("<tr> <td>" + checkbox + "</td><td>" + childData.StudentId +
"</td><td>" + childData.FirstName +" "+ childData.Lastname +
"</td><td>" + childData.Address +
"</td><td>" + childData.Gender +
"</td><td>" + childData.Age +
"</td><td>" + childData.Phone +
"</td><td>" + childData.Year +
"</td></tr>"
);
});
Output
Try this:
function BSIT(){
$("#stdlist").empty();
var chyear = $('#chyear').val();
$("#showtxt").html(chyear);
var ref = firebase.database().ref().child("course/BSIT");
ref.orderByChild("Year").equalTo(chyear).on("child_added", function(snapshot) {
var childData = snapshot.val();
$("#stdlist").append("<tr> <td>" + '<input type="checkbox">'+ "</td><td>" + childData.StudentId +
"</td><td>" + childData.FirstName +" "+ childData.Lastname +
"</td><td>" + childData.Address +
"</td><td>" + childData.Gender +
"</td><td>" + childData.Age +
"</td><td>" + childData.Phone +
"</td><td>" + childData.Year +
"</td></tr>"
);
});
I hope it will help you :)

jquery $.each not giving all the information in the table

Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read

jQuery after ajax plugin doesn't work

I'm using a plugin to rate values: http://www.radioactivethinking.com/rateit/example/example.htm
The following code works if I put directly into the HTML.
<li>
<p><strong>Product</strong>
<br/>
<input type="range" value="0" step="1" id="rateit" data-role="none">
<div class="rateit" id="rateitHover" data-rateit-backingfld="#rateit" data-rateit-resetable="false" data-rateit-ispreset="true"
data-rateit-min="0" data-rateit-max="5">
</div>
</p>
</li>
The code below doesn't work, it retrieves the default <input type="range"> by html.
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div class='rateit' id='" + 'rateIt' + item.id + "' data-rateit-backingfld='" + 'rateIt' + item.id + "' data-rateit-resetable='false' data-rateit-ispreset='true' " +
"data-rateit-min='0' data-rateit-max='5'></div></p></li>";
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
How do I turn this into that plugin? Thanks!
You have a syntax error on your 4th/5th line. Take a look at your "'s you have an extra.
info += "<li id='" + item.id + "'><p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div class='rateit' id='" + 'rateIt' + item.id + "' data-rateit-backingfld='" + 'rateIt' + item.id + "' data-rateit-resetable='false' data-rateit-ispreset='true' " +
"data-rateit-min='0' data-rateit-max='5'></div></p></li>";
Ok, I've found that this is some kind of bug or something. I've tested with another plugins and doesn't work either. I'm now using a better plugin, which is more easier.
https://github.com/wbotelhos/raty
The html is very simple: <div id="score"></div>, although it is necessary to call it on jQuery.
$("#score").raty({
score: function() {
return $(this).attr('data-rating');
}
});
I've tried to adapt it and make all IDs uniques:
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div id=" + 'score' + item.id + "></div></p></li>";
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
But continues not to work. I've tried in vain also:
$.getJSON(url, function(data){
$.each(data, function(index, item)
{
info += "<li id='" + item.id + "'>" +
"<p><strong>" + item.product + "</strong><br/>" +
"<input type='range' value='0' step='1' id='" + 'rateIt' + item.id + "'/>" +
"<div id=" + 'score' + item.id + "></div></p></li>";
$("#score" + item.id).raty({
score: function() {
return $(this).attr('data-rating');
}
});
});
$("#listviewA").append(info);
$("#listviewA").trigger("change");
$("#listviewA").listview("refresh");
});
Btw, I'm loading this function before page show..I don't know if that's the problem.
$(document).on("pagebeforeshow", "#main", function() {
$(function(){
get_info();
});
})

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() + '">');

Categories

Resources