How to store dataTable contents in a localstorage - javascript

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);

Related

How to add table row data to an array

Goal: get all table row (cell) data and add to an array
Problem: if there are more than 1 row, it over-writes previously added array entries in stead of adding it to the end of the array. This causes the array to have the last table row dataset duplicated/triplicated/etc (as many rows as there exist in table)
Setup:
I have a dynamic html table where a user can add rows by entering a user name and age and click the Add button. The Load button must get the table body elements and populate an object, where after a for loop must get the innerText, update the object and push() the object to the array. But this is the result:
Screenshot of console.log of array
let roleArr = [];
loadBtn.addEventListener("click", () => {
roleTableData();
});
function roleTableData() {
let test = tblRows.children;
const collectRoles = {
uName: "",
uAge: "",
};
for (let i = 0; i < test.length; i++) {
collectRoles.uName= test[i].children[0].innerText;
collectRoles.uAge= test[i].children[1].innerText;
roleArr.push(collectRoles);
}
}
Since you're using the same collectRoles object for each irraration, you are redefining all the objects, since they are references of the same object.
You can research "reference vs value in JavaScript" to better understand why this is so.
Here is how I would write your roleTableData function:
function roleTableData() {
roleArr = [...tblRows.children].map(tr => {
return {
uName: tr.children[0].innerText,
uAge: tr.children[1].innerText
};
});
}

Cross reference names on spreadsheets to get specific data points (looping through an array)

I have two sheets. Test Data has 3-4k entries of many columns of data and Order Changes has no data at all. I would like to search two specific columns on Test Data, a column of names and a column of yes or no. If column two of Test Data contains a 'yes' in the cell then the name of that person would be placed into a cell on order changes.
This is what I have so far:
function isThreshold(){
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test Data");
var cdata = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order Changes");
var lc = data.getLastColumn();
var lookUp = data.getRange(1,6,3,2).getValues();
lookUp.forEach(var info in lookUp){
}
Logger.log(lookUp);
}
I probably shouldn't loop through that many entries but I don't know of any other way. Should I combine the forEach loop with an if loop to get the desired result or use some other method?
I believe your goal as follows.
You want to retrieve the values from the cells "F1:G" of sheet "Test Data".
You want to search yes from the column "G" and when the column "G" is yes, you want to put the value of the column "F" to the sheet "Order Changes".
Modification points:
SpreadsheetApp.getActiveSpreadsheet() can be declared one time.
In this case, you can retrieve the values from the range of "F1:G" + data.getLastRow() of "Test Data", and create the array for putting to the sheet "Order Changes", and put it.
When above points are reflected to your script, it becomes as follows.
Modified script:
function isThreshold(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var data = ss.getSheetByName("Test Data");
var cdata = ss.getSheetByName("Order Changes");
var valuesOfTestData = data.getRange("F1:G" + data.getLastRow()).getValues();
var valuesForOrderChanges = valuesOfTestData.reduce((ar, [f, g]) => {
if (g.toLowerCase() == "yes") ar.push([f]);
return ar;
}, []);
if (valuesForOrderChanges.length > 0) {
cdata.getRange(1, 1, valuesForOrderChanges.length, valuesForOrderChanges[0].length).setValues(valuesForOrderChanges);
// or cdata.getRange(cdata.getLastRow() + 1, 1, valuesForOrderChanges.length, valuesForOrderChanges[0].length).setValues(valuesForOrderChanges);
}
}
In this modified script, from your question, it supposes that the columns "F" and "G" are the value of name and yes or no.
References:
getRange(a1Notation) of Class Sheet
reduce()

Dynamically add the values in titanium tableview

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);

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)

Add a row in Dojo datagrid

Struggling to find a bit of code to easily understand.
How do you add a row and clear all rows in a Dojo datagrid (version 1.4.2). Lets say the data is 2 columns with customerID and address.
I am using
dojo.data.ItemFileWriteStore
to store values in - but again not quite sure how this should be used.
It can't be that hard.
Cheers.
You can get the data store reference from the grid using grid.store, then you can use store.newItem() to create a new item in the store. This new item is added as a new row in the grid. For example, store.newItem({customerID : 1, address : "Somewhere"}).
To clear all the rows, you can either loop all the items in the data store and use deleteItem() to remove all the items, or use the internal function _clearData() in data grid to remove all the rows, or use setStore() to set a new empty store to the grid. I prefer to use a empty store to reset the grid.
The above answers are correct, but you also need to call save() on the write store to "commit" the change. When you save, a widget using the store (datagrid for example) will refresh itself.
Also, newItem() returns the new item you just created so if you don't want to pass an object to newItem just modify its return value, then save() the store.
Pseudo code:
var i = store.newItem({});
store.setValue(i,"newattribute1","new value");
store.setValue(i,"newattribute2","new value 2");
store.save();
Here is the relevant docs for ItemFileWriteStore which tell how to use newItem(), setValue(), and save().
Instead of deleteItem, you should use setStore(new ItemFileWriteStore()), but I suspect there is a memory leak when you do this, be careful. This makes a new blank store to be used with the grid.
I have finish one example about this... the code is here
//First we create the buttons to add/del rows
var addBtn = new dijit.form.Button({
id: "addBtn",
type: "submit",
label: "Add Row"
},
"divAddBtn");//div where the button will load
var delBtn = new dijit.form.Button({
id: "delBtn",
type: "submit",
label: "Delete Selected Rows"
},
"divDelBtn");
//Connect to onClick event of this buttons the respective actions to add/remove rows.
//where grid is the name of the grid var to handle.
dojo.connect(addBtn, "onClick", function(event) {
// set the properties for the new item:
var myNewItem = {
id: grid.rowCount+1,
type: "country",
name: "Fill this country name"
};
// Insert the new item into the store:
// (we use store3 from the example above in this example)
store.newItem(myNewItem);
});
dojo.connect(delBtn, "onClick", function(event) {
// Get all selected items from the Grid:
var items = grid.selection.getSelected();
if (items.length) {
// Iterate through the list of selected items.
// The current item is available in the variable
// "selectedItem" within the following function:
dojo.forEach(items, function(selectedItem) {
if (selectedItem !== null) {
// Delete the item from the data store:
store.deleteItem(selectedItem);
} // end if
}); // end forEach
} // end if
});

Categories