I have problem editing local storage data. I saved Array of Array-list in local storage and it works, or save. However, when i tried to edit, it only edit temporarily and the edited data disappear when i refresh the page and it shows the original data i saved
function editinfo(){
var name = document.getElementById("nameB").value;
var price = document.getElementById("priceB").value;
var quant = document.getElementById("quantityB").value;
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for (i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1]= price
pro[i][2] = quant;
} else{
console.log("There is no such data to edit");
}
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
// I saved information on local storage, I read data from server.
var bevInventory = $.getJSON('http://pub.jamaica-inn.net/fpdb/api.php?username=jorass&password=jorass&action=inventory_get');
function Info(){
var info = [];
bevInventory.done(function(result){
for(i = 0; i < result.payload.length; ++i){
if(result.payload[i].namn != ""){
var makeList = [result.payload[i].namn, result.payload[i].price, result.payload[i].count];
info.push(makeList);
}
}
var xx = window.localStorage.setItem("done", JSON.stringify(info));
})
return info;
}
One solution is to check first, and add data to local storage if it does not exist. Like this
function editinfo() {
var name = 'bob';
var price = 1;
var quant = 2; // loaded dynamically from page.
if (window.localStorage.hasOwnProperty("done")) {
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for(i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1] = price
pro[i][2] = quant;
}
}
} else {
pro = [[name, price, quant]];
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
Your code fails if there is no "done" data initially in localStorage. JSON.parse() parses null (because of no data) and then error occurs on line
pro.length
So it's better to check if it's a first launch and there is no data:
if (!pro) {
pro = [];
}
Example here
After first executing of editinfo() data successfully saves in localStorage.
Related
I read some other similar questions but I couldn't understand it how to do it on my code.
I have a spreadsheet that will be filled with an app, I am using appendRow to add rows but now I need to update the entire row with new array of data, if the variable pid(Código) from the row I am receiving exists on the spreadsheet, I need to update it, not add a new row.
function doGet(request) {
var sheet = SpreadsheetApp.openById("DOCUMENT_ID");
var data = sheet.getActiveSheet().getDataRange().getValues();
var updateIndex;
try{
var pid = request.parameter.pid;
var nome = request.parameter.nome;
var desc = request.parameter.desc;
var marca = request.parameter.marca;
var tipo = request.parameter.tipo;
var preco = request.parameter.preco;
var ativado = request.parameter.ativado;
var rowData = [pid, nome, desc, marca, tipo, preco, ativado];
// loop through all rows to check the column "pid" has the value of variable "pid"
for(var i = 1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex = i;
}
}
// Update the row here with "rowData"?
sheet.
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
function doGet(request) {
var sheet=SpreadsheetApp.openById("DOCUMENT_ID");
var data=sheet.getActiveSheet().getDataRange().getValues();
var updateIndex;
try{
var pid=request.parameter.pid;
var nome=request.parameter.nome;
var desc=request.parameter.desc;
var marca=request.parameter.marca;
var tipo=request.parameter.tipo;
var preco=request.parameter.preco;
var ativado=request.parameter.ativado;
var rowData=[pid, nome, desc, marca, tipo, preco, ativado];
for(var i=1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex=i;
break;
}
}
sheet.getRange(updateIndex+1,1,1,rowData.length).setValues([rowData]);
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
Sheet.getRange(start row,start col,number of rows,number of columns)
When pid is included in the values of the column "A", you want to replace the row with rowData.
When pid is NOT included in the values of the column "A", you want to append new row with rowData.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modified script:
When your script is modified, it becomes as follows.
function doGet(request) {
var sheet = SpreadsheetApp.openById("DOCUMENT_ID");
var range = sheet.getActiveSheet().getDataRange(); // Added
var data = range.getValues(); // Modified
var updateIndex = 0; // Modified
try{
var pid = request.parameter.pid;
var nome = request.parameter.nome;
var desc = request.parameter.desc;
var marca = request.parameter.marca;
var tipo = request.parameter.tipo;
var preco = request.parameter.preco;
var ativado = request.parameter.ativado;
var rowData = [pid, nome, desc, marca, tipo, preco, ativado];
for(var i = 1; i < data.length; i++){
if(data[i][0] == pid){
data[i] = rowData; // Added
updateIndex = i;
}
}
if (updateIndex != 0) { // Added
range.setValues(data);
} else {
sheet.appendRow(rowData);
}
} catch(e){
console.log(e);
}
// In your script, "result" is not declared. Please be careful this.
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
Note:
In your script, result is not declared. Please be careful this.
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. So please be careful this.
If I misunderstood your question and this was not the direction you want, I apologize.
My solution:
function doGet(request) {
// Modified
var sheet=SpreadsheetApp.openById("DOCUMENT_ID").getActiveSheet();
var data=sheet.getDataRange().getValues();
//
var updateIndex;
try{
var pid=request.parameter.pid;
var nome=request.parameter.nome;
var desc=request.parameter.desc;
var marca=request.parameter.marca;
var tipo=request.parameter.tipo;
var preco=request.parameter.preco;
var ativado=request.parameter.ativado;
var rowData=[pid, nome, desc, marca, tipo, preco, ativado];
for(var i=1; i < data.length; i++){
if(data[i][0] == pid){
updateIndex=i;
break;
}
}
// Modifed
sheet.getRange(updateIndex + 1, 1, 1, rowData.length).setValues( [rowData] );
//
} catch(e){
console.log(e);
}
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType);
}
I managed to successfully call a function whenever a page is scrolled to its maximum, but I don't know how to make that function call the data from the database and them in the correct order. Here is my current code:
function loadMoreData(num) {
var rawDataRef = db.ref("chat/"+group);
rawDataRef.on("value", function(data) {
if (data.hasChildren() == true) {
var uid = firebase.auth().currentUser.uid;
var keys = Object.keys(data.val());
var startAt = keys[num-1];
var dataRef = db.ref("chat/"+group+"/").startAt(startAt).limitToLast(15);
dataRef.on("value", function(snapshot) {
var data = snapshot.val();
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (data[k].uid == uid) {
$("#data").prepend('<div class="dataByMe">'+data[k].data+'</div><br><br>');
} else if (data[k].uid != uid) {
$("#data").prepend('<div class="dataByOthers">'+data[k].data+'</div><br><br>');
}
}
});
}
});
}
My code shows the last 25 data when the page is first loaded, and then, when the page is scrolled to the top, I need to load 15 more data before the point where the last 25 data starts, and show them in the order of latest data at the bottom. How exactly do I do this?
Note: The dataByMe and dataByOthers classes are because I need to style them differently.
I am uploading and displaying a csv file using angular. The Upload button/function takes care of reading and parsing the csv so the html can display. However, the table is not displaying the with the initial click, it requires a second click of the upload button to display. When I log in console, it shows that the array of objects is created after the first click.
vm.upload = function () {
var fileUpload = document.getElementById("fileUpload");
var reader = new FileReader();
reader.onload = function (e) {
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(',');
for(var i = 1;i<lines.length;i++){
var obj = {};
var currentline = lines[i].split(',');
for(var j = 0;j < headers.length; j++){
obj[headers[j]] = currentline[j];
}
if (obj[headers[1]] == undefined){
continue;
}
result.push(obj);
}
vm.head = headers;
vm.data = result;
console.log(result);
console.log(headers)
console.log(vm.data)
}
reader.readAsText(fileUpload.files[0]);
vm.editTable = false
vm.display = true;
};
Because your scope changes are not happening as a direct (i.e. non-async) result of a user interaction, you probably been to use $scope.$apply to trigger a UI update.
Jim Hoskins has a good blog post about this:
Jim's Blog
so when trying to go through a loop that checks, updates, and posts data to my Firebase storage, it seems that whenever I try to use the Firebase.update(), then it messes with my for loop and it repeats incrementations or doesn't increment at all. Any advice?
My Code:
var j = 0;
var k = 0;
var l = 0;
var m = 0;
var setDict = {};
for(var h = 0; h < teamWinNames.length; h++)
{
console.log(j);
console.log(h);
console.log(meWinList[j]);
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
var tempName = teamWinNames[h];
tempRef.once("value", function (teamWinSnapshot)
{
var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
console.log(exists);
if(exists == true)
{
console.log("Here");
var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
console.log(tempVal);
//var tempValue = obj[tempname][tempchamp];
//console.log(tempValue);
}
else
{
setDict[tempName] = '1-0-0-0';
console.log(setDict);
}
});
if(h != 0 && (h+1)%4 == 0)
{
sendUpdate(setDict, meWinList[j], username);
setDict = {};
j++;
}
}
and the function that makes the update:
function sendUpdate(data, champ, username)
{
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
tempRef.child(champ).update(data);
}
The problem is that you are getting your data in the for loop and also changing it inside the loop. This means that the data you are using in your loop changes with each iteration. And as an added bonus you get the effects of the asynchronous nature of firebase that can look something like this:
Get data (1)
Get data (2)
Update data (1)
Get data (3)
Update data (3)
Update data (2)
To prevent all this i suggest putting the for loop inside the tempRef.once function like this: (pseudo code)
tempRef.once{
Loop through data{
Change data
}
Update data
}
This means you only have to get the data once and update it once.
This may seem a very newbie question, but I'm stuck with it. I've got this code to show a check list in a UI and insert the paragraphs of one or more documents into another target document:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
ScriptProperties.setProperties({'theses': itemsSelected}, true);
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
But when I call these functions inside my main function, I got a red message (in my language): service not available: Docs and, after the UI from showList() is closed, nothing more happens with my code (but I wanted the main functions continues to run). I call these functions this way:
if (theses == 1){
showList();
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
}
showURL(docName, link); // Shows document name and link in UI
So, how can I fix that? How can I get the code run until the line showURL(docName, link);?
showList();
This function creates only Ui.
You are setting the script properties only in the Server Handler which executes on the click of submit button. Since then:
ScriptProperties.getProperty('theses');
will hold nothing. So you need to call these lines:
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
Inside server handler or put them inside a method and call the method from the server Handler.