Javascript Pushing Objects to Array - javascript

I'm unable to push objects to an array and i can't figure out why. At the moment, the result (records) repeats the last instance of the each loop.
JSFiddle
HTML
<div data-provider="prv1"></div>
<div data-rating="rtn1"></div>
<div data-price="prc1"></div>
<div data-provider="prv2"></div>
<div data-rating="rtn2"></div>
<div data-price="prc2"></div>
<div data-provider="prv3"></div>
<div data-rating="rtn3"></div>
<div data-price="prc3"></div>
<div data-provider="prv4"></div>
<div data-rating="rtn4"></div>
<div data-price="prc4"></div>
Javascript (w/ jQuery)
(function(){
var sort = $(".sort select");
var provider = $("[data-provider]");
var rating = $("[data-rating]");
var price = $("[data-price]");
var records = [];
var record = {};
$(provider).each(function(index, value){
record.provider = $(provider).eq(index).data("provider");
record.rating = $(rating).eq(index).data("rating");
record.price = $(price).eq(index).data("price");
records[index] = record;
});
})();

In your loop you set each index to be equal to record. Since the scope of record is the anonymous function, it will be the same object for each index.
What you want is for the scope to be the function provided to .each
Like this fiddle
$(provider).each(function(index, value){
var record = {};
...
});

Related

Displaying data on the page from the data gotten from parse

I have offers table and users table on parse server. I did a query for he offers table and it worked great (both console log and html - I had issues with async and the Q.promise helped). Now I'm trying to add two elements that are in the users table. I get it on the console, but not on the page. Here is what I have on the offers.service:
this.getAllOffers = function () {
var Q = $q.defer();
console.log('getAllOffers called');
//all offers filter is selected
this.allOffersFilter = false;
var offers = Parse.Object.extend("Offer");
var exchanges = Parse.Object.extend("Exchanges");
var users = Parse.Object.extend("User");
var query = new Parse.Query(offers);
var userQuery = new Parse.Query(users);
var results = [];
query.descending("createdAt");
query.limit(4);
userQuery.find().then(function(users) {
for (i = 0; i < users.length; i++) {
foundUsers = users[i];
query.find().then( function(offers){
for(i = 0; i < offers.length; i++){
found = offers[i];
var result = {};
result.date = found.get("createdAt");
result.price = found.get("price");
result.status = found.get("accepted");
result.lastName = foundUsers.get("lastName");
result.companyName = foundUsers.get("companyName");
console.log(result.companyName);
console.log(result.price);
}
});
results.push(result);
}
Q.resolve(results);
});
return Q.promise;
};
Then my HTML:
<!--List of offers-->
<div class="col-md-3">
<h4>List of offers</h4>
<div ng-if="offersList">
<div ng-repeat="offer in offersList">
<div class="offer card">
<div>{{offer.username}}</div>
<div>{{offer.companyName}}</div>
<div>{{offer.date}}</div>
<div>{{offer.price}}</div>
<div>{{offer.status}}</div>
</div>
</div>
</div>
<div ng-if="!(offersList)">There are no offers</div>
</div>
Then my component:
angular.module('offersPage')
.component('offersPage', {
templateUrl: 'pages/offers-page/offers-page.template.html',
controller: function(AuthService, PageService, OffersService,
$scope) {
// Functions for offers-page
// Check if user is logged in and verified on page load
AuthService.userLoggedin(function(loggedIn, verified) {
if(!verified) {
PageService.redirect('login');
}
});
this.$onInit = function() {
OffersService.getAllOffers().then(function(offersList) {
$scope.offersList = offersList;
});
}
}
});
THANKS IN ADVANCE !
You are resolving $q before results is populated, so, you list is empty.
I don't know about Parse server, but if userQuery.find().then is async, then need to move Q.resolve(results); inside it, or probably inside query.find().then.
When you do an ng-if in angularjs it literally takes out the element and when it puts it in it is as a child scope. To fix this you need to make sure and put $parent on any child element inside an ng-if. See below. Make sure to use track by $index to when you are doing repeats its good practice. Also notice you dont need to $parent anything in the repeat since it is referencing offerwhich is defined.
Code:
<div ng-if="offersList">
<div ng-repeat="offer in $parent.offersList track by $index">
<div class="offer card">
<div>{{offer.username}}</div>
<div>{{offer.companyName}}</div>
<div>{{offer.date}}</div>
<div>{{offer.price}}</div>
<div>{{offer.status}}</div>
</div>
</div>
</div>

using function arguments inside .each() jQuery

I get certain arguments in a function and when i try to use them inside .each() which loops through my ajax response. when i log the argument inside the each function i get undefined.
function updateCandidateDetails(data,can_id){
var candidate_id = can_id;
var updated_name,updated_phone,updated_email;
$.each(data,function(key,value){
$.each(value,function(index,titleObj){
var updated_name = titleObj.name;
var updated_phone = titleObj.phone;
var updated_email = titleObj.email;
console.log(updated_name);
console.log(candidate_id);
var panel = $('div#'+candidate_id+'.panel');
panel.find('p#card_name').val();
panel.find('div.card_details p#card_phone').val(updated_phone);
panel.find('div.card_details small#card_email').val(updated_email);
});
});
}
Here is my html
<div class="panel" id="{{$candidate->id}}">
<div class="card_details">
<b><p id = "card_phone">{{$candidate->phone}}</p></b>
<b><small id="card_email">{{$candidate->email}}</small></b><br><br>
</div>
</div>
With can_id i am not able to update the value using val() function since finding the parent panel needs candidate_id

Angularjs firebase array object always display false

Hi i having problem when i retrieve data from firebase in console.log($scope.statusbaca) it display 2 query true and false. but when it showing in the app it only display false. Sorry for my bad english. English is not my native language. Hope you understand my problem
App return false but console log display true and false
and this is my code
Template
<div ng-repeat= "item in users">
<div class="list card" style="padding:1%;">
<div class="col-50" style="float:left;">
<h5>{{item.displayName}} - {{item.handphone}}</h5>
<h5>{{item.email}}</h5>
</div>
<div class="col-33" style="float:right; position: relative;" ng-repeat = "datas in statusbaca">
<h5>{{datas}}</h5>
</div>
</div>
</div>
Controller
var rootRef = new Firebase('https://example-app.firebaseio.com/');
var childUsers = rootRef.child('users');
var childDate = rootRef.child('tanggal');
var rekapId = $stateParams.rekapId;
console.log(rekapId);
childDate.child(rekapId).child('tanggalBaca').once('value',function(snap){
$timeout(function() {
var snapshot= snap.val();
$scope.tanggal = snapshot;
console.log($scope.tanggal);
myAfterFunction();
});
})
function myAfterFunction(){
var dates = $scope.tanggal;
console.log(dates);
var rekapUsers = childUsers.on('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key();
console.log(key);
var childStatus = childUsers.child(key+'/status/'+dates);
childStatus.on('value',function(grandsnap){
var snapval =grandsnap.val();
$scope.statusbaca = snapval;
$scope.key = key;
console.log($scope.statusbaca);
console.log($scope.key);
})
})
var snapshotVal = snapshot.val();
$scope.users =snapshotVal;
console.log($scope.users);
})
}
Any idea what's wrong with my code and how to fix this? thanks
I'm not sure if this will fix it but your div elements are unbalanced.
You should add a ending div element like this,
<div class="col-33" style="float:right; position: relative;" ng-repeat = "datas in statusbaca">
<h5>{{datas}}</h5>
</div>
Also, I can't find some of the variables referenced by the HTML in the JavaScript and rather than having your
value output like this:
<h5>{{datas}}</h5>
you should have it like this:
<h5>{{datas.THE NAME OF YOUR KEY:VALUE PAIR}}</h5>
I can't test it since you're using firebase but, I would do quick run through with your code.

Check each div for id based upon values within an array

I'm creating a set of tabs based upon an existing set of categories with the below JS. I need to extend this to target specific id's within the DIV id based upon values from a JS array.
$("#categories div[id^=category]:not(:first)", this).hide();
var cats = $('#categories div[id^=category]');
cats.each(function () {
var anch = $(this).find('h3 a').eq(1).clone();
anch[0].rel = this.id;
$('<li/>').append(anch).appendTo('#tabs');
});
The html:
<div id="category_1">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 1 Title
</h3>
<div>
...
</div>
</div>
<div id="category_2">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 2 Title
</h3>
<div>
...
</div>
</div>
I've got a JS array ready by adding:
var catsList = '{$cats}'; // comma separated list of numbers generated in PHP - returns 1,4,8 currently.
var catsArray = catsList.split(',');
How would I convert the below, to check for each item within catsArray ?
var cats = $('#categories div[id^=category]');
Something like
var cats = $('#categories div[id^=category_'+catsArray+']');
but obviously checking each item within the array and not the entire array as that's doing.
You could use that as IDs have to be unique on context page:
var cats = $('#category_'+catsArray.join(',#category_'));
DEMO
you probably want the each function
$.each(catsArray,function(index, item) {
var cats = $('#categories div[id^=category_'+item+']');
});
Depending on how you using this a for loop will do it also:
for (var i = 0; i < catsArray.length; i++) {
var catIndex = catsArray[i];
var cats = $('#categories div[id^=category_'+catIndex +']');
}

Adding get() to line causes "is not a function" error

This is the start of an inventory system I am working on. Basically it takes an array with items and quantities in a compressed form and outputs the items into an item div.
Running the below produces no error:
$('.item_amount').html(collection[itemName].amo);
Adding the get() method after the selector like so:
$('.item_amount').get(i).html(collection[itemName].amo);
produces "$(".item_amount").get(i).html is not a function".
This is what the line is altering:
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
The line that is causing the error is located in a for loop that loops through all the keys in an array. Then outputs the item quantity from the array in the item_amount div based on the index stored in the variable "i". The for loop also creates an object for each item in the array and puts in the a collection object.
Full code below:
<body>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<div class="item">
<img src="" class="item_image"/>
<div class="item_amount"></div>
</div>
<script type="text/javascript">
var collection = new Object();
function makeItem(itemName, id, amo) {
collection[itemName] = new item(id, amo);
}
function item(id, amo) {
this.id = id;
this.amo = amo;
}
var inventoryCom = "368.9,366.15,384.32"; //compressed inventory
var inventoryArr = inventoryCom.split(',');
for(var i=0; i < inventoryArr.length; i++) {
var itemName = 'item' + (i + 1); //unique name for each item
var itemArr = inventoryArr[i].split('.');
makeItem(itemName, itemArr[0], itemArr[1]);
$('.item_amount').get(i).html(collection[itemName].amo);
}
</script>
</body>
.get(i) returns DOM element, which doesn't have .html() method - that's what js engine wants to say to you.
You need to use .eq(i) instead. Like
$('.item_amount').eq(i).html(collection[itemName].amo);
or
$('.item_amount:eq(' + i + ')').html(collection[itemName].amo);
This line may be a problem
var itemName = 'item' + (i + 1); //
This may increment the array count out of the upper bound. check the itemName value.
Also try to add an alert for this
collection[itemName].amo

Categories