Dynamically add the values in titanium tableview - javascript

I have listed out the categories on 1st page, subcategories on 2nd page and products on 3rd page. Now I have added the products to the cart. now will go back to categories page again and will add the products to cart. If we need to view the items in the cart, we can declare a global array[] and will add the data's to that array[]. But here if I have added the 3 items means the final item which was added recently that item only showing in the cart list items page. But I want to display the added 3 items. Can you please check my code and find out my issue.
Ti.App.data = [];
data=[
{title:productlist_product,
price:productlist_product_price,
quantity:selectedqty},
];
var myObjectString = JSON.stringify(data);
EDIT:
Ti.API.info("DATA-length"+" "+data.length);
Here am getting the value as 1 .But in the cart page having the 3 products. i need to add that 3 products value to data[].Can you please give me solution ?
EDIT:
Now i have added the values dynamically in the array[] using below code.
data = [
{title:productlist_product,
price:productlist_product_price,
image:productlist_product_image,
quantity:selectedqty},
];
// append new value to the array
data.push({title:productlist_product,
price:productlist_product_price,
image:productlist_product_image,
quantity:selectedqty});
// display all values
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
var myObjectString = JSON.stringify(data);
Ti.API.info("PRICE"+" "+myObjectString);
Now i have added the same product with different quantity means that the product is listed separately. But if i have added same product with different quantity means want to list out the product name in the list single time .but the quantity is need to update on the products.
For Eg:
if i have added the "Android development " product with 2 quantity in the cart. Again i will add the same product with "Android development" product with 4 quantity means the list is displaying right now :
PRICE [{"title":"Android development","quantity":2},
{"title":"Android development","quantity":4}]
But i want to looking like the below :
PRICE [{"title":"Android development","quantity":6}]

You must assign the array of data to the table's data property in order to display these objects as tableView rows. Let's say:
Ti.UI.backgroundColor = 'white';
var win = Ti.UI.createWindow();
var tableData = [ {title: 'Apples'}, {title: 'Bananas'}, {title: 'Carrots'}, {title: 'Potatoes'} ];
var table = Ti.UI.createTableView({
data: tableData});
win.add(table);
win.open();
Or, you may also want to add rows using table.setData
customTableView.setData(data);
var customTableView = Titanium.UI.createTableView({ BackgroundColor:'White', style: Titanium.UI.iPhone.TableViewStyle.GROUPED, });
data.push({title:productlist_product, price: productlist_product_price,quantity: selectedqty});
customTableView.data = data;

Try this,
var productData = [
{Product_Name: 'Apples',Product_Price :50,Product_qty :5},
{Product_Name: 'Banana',Product_Price :40,Product_qty :5},
{Product_Name: 'Carrots',Product_Price :90,Product_qty :5}
];
var tableData = [];
for(var i=0;i<data.length;i++){
var tableRow = Ti.UI.createTableViewRow({
title :"Name :"+data[i].Product_Name+" Price : "+data[i].Product_Price,
});
tableData.push(tableRow);
}
var tableView = Ti.UI.createTableView({
data: tableData
});
win.add(tableView);

Now i have added the values dynamically in the array[] using the below code.
data = [
{title:productlist_product,
price:productlist_product_price,
image:productlist_product_image,
quantity:selectedqty},
];
// append new value to the array
data.push({title:productlist_product,
price:productlist_product_price,
image:productlist_product_image,
quantity:selectedqty});
// display all values
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
var myObjectString = JSON.stringify(data);
Ti.API.info("PRICE"+" "+myObjectString);

Related

AngularJS How to group/organize items in object in order to show them in the view

I have a URL with some parameters like this one:
http://localhost:9000/#/checkout/?title1=Sodadrink&quantity1=2&price1=129.95&title2=PolaryteGlasses&quantity2=1&price2=59.95#%2F
and I'm getting them with $location.search(), which returns them just fine in an Object like:
Object
price1: "129.95"
price2: "59.95"
quantity1: "2"
quantity2: "1"
title1: "Sodastream"
title2: "Polaryte – Óculos de Sol"
__proto__: Object
This is cool, but now I need to group each item like:
[item]
title : Sodastream
price : 129.95
quantity : 1
[item]
title : ---
price : ---
quantity : ---
I'm stuck in this part, I've though of counting the total items inside the object, 6, and them group them in groups of 3 by creating a new Object, but didn't work out.
Can you help me? Thanks.
Since the number of items in the URL may vary, it is best to not hardcode any number. For this, I am also assuming that every item has 3 properties - title, price and quantity.
Try this:
var numOfItems = Object.keys(input).length/3; // for example, 6 properties will mean 2 items
var output = [];
for (var i = 1; i <= numOfItems; i++) {
if (input["title"+i]) {
output.push({title: input["title"+i], price: input["price"+i],quantity: input["quantity"+i]})
}
}
The output array should contain the objects in the exact way you specified.
You will have to write a bit of javascript to do that.
Assuming that your object from above is called inputs
const MAX_ITEMS=9;
var outputs = [];
for (var i=1,i<MAX_ITEMS;i++) {
if (inputs["item"+i]) {
outputs.push({item: inputs["item"+i], price: inputs["price"+i],quantity: inputs["quantity"+i]})
}
}
Your data will be in the outputs variable

Joining an array on another array's value

I am using mongodb and am building an application with two collections: users and items.
I'd like for users to be able to save items that they like and go to their saved items page where the items would be displayed in the reverse order that they were saved (last saved appears first).
At the moment, I am adding every saved item's id along with the savedDate to the user's profile savedItems array like so:
user profile
{
savedItems: [{id: "", savedDate: ""}, {id: "", savedDate: ""}, etc...]
}
Whenever I need to retrieve those items, I query the items collection for objects with ids $in this array. Like this:
var items = Items.find({_id: {$in: _.pluck(user.savedItems, 'id')}});
The problem here is that I can't order those items according to the addedDate.
So is it possible to map the addedDate onto every object of the retrieved items?
(Something like: if retrievedItems.id == savedItems.id, then push the addedDate there.)
Which would result in an items array like this:
[
{id:"", itemName:"", price: "", [...], savedDate: ""},
{id:"", itemName:"", price: "", [...], savedDate: ""},
[...]
]
Thank you.
JSFIDDLE
I created two function to help you do it:
function mergeDates(listDates, listItems) {
for (var i = 0; i < listDates.length; i++) {
var index = findListIndex(listItems, listDates[i].id);
if (index != null) listItems[index].savedDate = listDates[i].savedDate;
}
return listItems;
}
function findListIndex(listItems, id) {
for (var i = 0; i < listItems.length; i++) {
if (listItems[i].id == id) return i;
}
return null;
}
The first one, mergeDates, takes your first list wich contains the date, the second list, listItems, is the list of your items.
I loop the list with dates, and for each items in it, i call a second function that return the index of the same element in the second list, so findListIndex will search all element and return it's index when he find the same id.
Now the function mergeDates, with the newly found index, will add the value savedDate to your listItems and make it equals to the one on the listDates !
Then the function return the list with all the info of the items, including the dates!
Here is how to call the function:
var listWithDate = mergeDates(savedItems, items);
Hope it helps !

How to store dataTable contents in a localstorage

I want to do is to store all the data in the table to a localstorage so that if i refresh or closed the browser and reopened again the contents are still their before it was refresh or closed. And if i delete a specific row it should be deleted also in the localstorage so that it wont comeback if i refresh the page.
My problem is, it only store 1 row of the table in the localstorage the other rows is not saved.
current output: http://jsfiddle.net/4GP2h/57/
In a rush? Here's the fiddle :
Right now, you're setting the "dataSet" localStorage item to the last row added by the user:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"
];
oTable.row.add(data).draw();
//Assignment operator!
var dataset = JSON.stringify(data);
localStorage.setItem('dataSet', dataset);
Thus, only one row gets saved. Instead, you need to accommodate for multiple rows using a multi-dimensional array.
Outputting the data from the "dataSet" localStorage item:
//Use a try/catch loop to make sure that no errors come up while parsing the JSON of our localStorage
var dataSet;
try{
dataSet = JSON.parse(localStorage.getItem('dataSet')) || [];
} catch (err) {
dataSet = [];
}
/*
I did not add this in here, but you might want to since if our item returns an empty array, it either has an empty array in it, in which case the following code won't affect anything, or it has a localStorage item we don't want in it, in which case this will fix that.
if (!dataSet.length) localStorage.setItem('dataSet', '[]')
*/
$('#myTable').dataTable({
"data": [],
[...]
});
oTable = $('#myTable').DataTable();
//Loop through dataSet to add _all_ of the rows.
for (var i = 0; i < dataSet.length; i++) {
oTable.row.add(dataSet[i]).draw();
}
Adding data to the "dataSet" localStorage item:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"
];
oTable.row.add(data).draw();
//Push the new data into dataSet. DO NOT assign dataSet to data.
dataSet.push(data);
//Update the localStorage item.
localStorage.setItem('dataSet', JSON.stringify(dataSet));
Removing data from the "dataSet" localStorage item:
var row = $(this).closest('tr');
//Find the index of the row...
var index = $("tbody").children().index(row);
oTable.row(row).remove().draw();
//...and remove it from dataSet.
dataSet.splice(index, 1);
localStorage.setItem('dataSet', JSON.stringify(dataSet));
Well, your problem is that you're saving the dataset as the current row every time you hit the save button:
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"];
oTable.row.add(data).draw();
var dataset =JSON.stringify(data);
localStorage.setItem('dataSet', dataset);
Try appending the latest row to the total dataset and saving that instead,
I save it to localStorage like this:
var tableTotal = $('#orders_table').DataTable().rows().data();
var jsonTable = JSON.stringify(tableTotal);
localStorage.setItem("key", jsonTable);

extjs select record from first grid and copy the selected to second grid

now I have 2 grid panels. I want to select the some records of the first grid by using getselectionmodel() and the selected records will be load to the second grid and recreate a new grid.
are there any ways can load the selected records into second grid store?
I am using extjs3
you can call [[your first grid]].getSelectionModel().getSelections(), it will return an array of records
then you need to convert this array of records to a second array, let's call it data, readable by the reader of the second store.
So suppose your second store is an Ext.data.ArrayStore
var store2 = new Ext.data.ArrayStore({
fields: [ { name: 'field1' }, { name: 'field2' } ]
});
your convert function will be
function convert(records){
var record;
var data = [];
for (var i = 0; i < records.length; i++) {
record = records[i];
data.push([record.get('your field'), record.get('another field')]);
}
return data;
}
then on the second grid you can call .getStore().loadData(data)

Getting corresponding values from two different objects

I have returned an object from an ajax call that is the combination of two different arrays' of objects. One is Jobs and the second is the corresponding Customer Records for those jobs. The returned object is formatted like so..
{ "jobs" : [
{jobID: 1,
jobLocation: here
},
{jobID: 2,
jobLocation: there
}
],
"customers" : [
{customerID:1,
customerName:Tom
},
{customerID:2,
customerName:Sally
}
]
}
The items in the job array are sequentially related to the customers in the customer array. (i.e. the first customer owns the first job) How can I iterate or parse then iterate over this object to make list objects<li>'s that have are composed of a field from the jobs array and a field from the corresponding object of the customers array? thank you
A plain, old for-loop might do the job:
var customers = obj.customers;
var jobs = obj.jobs;
var $ul = $("<ul></ul>");
for (var i = 0; i < customers.length; i++) {
var customer = customers[i];
var job = jobs[i];
var $li = $("<li></li>").text(customer.customerName + " - " + job.jobLocation);
$li.appendTo($ul);
}
$("#result").append($ul);
See http://jsfiddle.net/XpQms/

Categories