How to delete localstroage in array - javascript

I keep array localstorage. I want to delete an element from the array list on another page. My code is below but delete function does not work why?
push.js
existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
entry = {
"adi":path,
};
localStorage.setItem("entry", JSON.stringify(entry));
existingEntries.push(entry);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
delete.js
delete: function (e) {
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if (dataSource[i].adi == del) { dataSource.splice(i, 1); }
}
// insert the new stringified array into LocalStorage
localStorage.getItem("allEntries") =
JSON.stringify(existingEntries);
}

var dataSource = JSON.parse(localStorage.dataSource); //whatever data you want
var del = e.itemData.adi //The information of the clicked element is retrieved.
for (var i = 0; i < dataSource.length; i++) {
if(del === persons[i].name){ //look for match with name
dataSource.splice(i, 1);
break; //exit loop since you found the person
}
localStorage.getItem("allEntries") = JSON.stringify(existingEntries); // insert the new stringified array into LocalStorage
}

Related

Determine if a string is in an array using Jquery

I have the following code:
function checkIfUnitCostItemsAreZero(finaliseIDList)
{
var selectedItems = finaliseIDList;
selectedItems = $.makeArray(selectedItems); //array is ["-2,-3"]
var getItem = $("#builderItemsList .listItem");
for (i = 0; i < getItem.length; i++)
{
var currentItem = ($(getItem[i]).attr("key"));
if (currentItem.indexOf(selectedItems) > -1)
{//currentItem = "-2" then "-3"
var unitCost = $(getItem[i]).attr("unitcost");
console.log(unitCost);
unitCost = parseFloat(unitCost);
if(unitCost==0.00)
{
return true;
break;
}
}
}
return false;
}
selected item currently equates to the following:
selectedItems = ["-2,-3"]
And further down, currentItem is evaluated at:
"-2", and the next loop "-3".
In both instances, neither go into the if statement. Any ideas why?
Courtesy of Hossein and Aer0, Fixed using the following:
String being passed in as a single value. Use split to seperate it for array.
Modify the if clause.
function checkIfUnitCostItemsAreZero(finaliseIDList)
{
var selectedItems = $.makeArray(finaliseIDList.split(','));
var getItem = $("#builderItemsList .listItem");
for (i = 0; i < getItem.length; i++) {
var currentItem = ($(getItem[i]).attr("key"));
if (selectedItems.indexOf(currentItem) > -1)
{
var unitCost = $(getItem[i]).attr("unitcost");
unitCost = parseFloat(unitCost);
if(unitCost==0.00)
{
return true;
break;
}
}
}
return false;
}

Save change in custom list display using local storage

I am trying to create a customizable list with links that can be hidden using a class if you click in a button. Also the list have a sortable option that you can move the links on the list, which saves to localstorage.
The problem is that I don't know how to save the class change with the list order in the localstorage if you click the "add/remove" button on each li.
Also, if anyone can help me improve the code I will be grateful, I am a newbie with localstorage and only managed this with a lot of reading in tutorials and documentation.
Here's a working example:
http://codepen.io/RogerHN/pen/EgbOzB
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
list.appendChild(itemsArr[i]);
}
}
}
}
$('.list-block.sortable').on('sort', function () {
var newIdsOrder = [];
$(this).find('li').each(function(){
newIdsOrder.push($(this).attr('data-id'));
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newIdsOrder));
});
You want something like this:
var myApp = new Framework7({
swipePanel: 'left'
});
// Export selectors engine
var $$ = Dom7;
var mainView = myApp.addView('.view-main');
var list = document.getElementById('linklist');
var items = list.children;
var itemsArr = [];
for (var i in items) {
itemsArr.push(items[i]);
}
// localStorage
var ls = JSON.parse(localStorage.getItem('userlist') || '[]');
var classes = JSON.parse(localStorage.getItem('classes') || '["","","","","","","","","",""]');
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
if(itemsArr[i].dataset !== undefined){
if (ls[j] === itemsArr[i].dataset.id) {
itemsArr[i].className = classes[i];
list.appendChild(itemsArr[i]);
// handle [add/remove] thing
if (classes[i] != "") {
$(itemsArr[i]).find(".checky").removeClass("selected");
}
}
}
}
}
$('.list-block.sortable').on('sort', saveInfo);
$(".restore").click(function(e) {
$(".confirm").show();
$(".shadow").show();
});
$(".no,.shadow").click(function(e) {
$(".confirm").hide();
$(".shadow").hide();
});
$(".yes").click(function(e) {
$(".confirm").hide();
});
$(".lbl").click(function(e) {
$(".toggle-text").toggleClass("blue");
$(".restore").toggle();
$(".checky").toggle();
$("li.hidden").toggleClass("visible");
});
$('.checky').click(function() {
if (!$(this).hasClass("selected")) {
$(this).parent().removeClass("hidden").addClass("visible");
}
else {
$(this).parent().addClass("hidden visible");
}
$(this).toggleClass("selected");
saveInfo();
});
function saveInfo() {
var newUserList = [];
var newClassList = [];
$("#linklist").find('li').each(
function() {
newUserList.push($(this).attr('data-id'));
if ($(this).hasClass("hidden")) {
newClassList.push("hidden");
}
else {
newClassList.push("");
}
});
// store in localStorage
localStorage.setItem('userlist', JSON.stringify(newUserList));
localStorage.setItem('classes', JSON.stringify(newClassList));
console.log("saved.");
}
function reset() {
console.log("Removing data from local storage.");
localStorage.setItem('userlist', '["1","2","3","4","5","6","7","8","9","10"]');
localStorage.setItem('classes', '["","","","","","","","","",""]');
window.location.reload(true);
};
Codepen
Technically, I should've added explanation...

Javascript: Pushing items to an Array doesn't work

I'm basically trying to loop through an array to check if an item already exists:
If the the item exists, remove it
If the item does not exist, push it to the array
However my code only allows me to add one item only. It ignores every other value I'm trying to add.
var inclfls = []; //new empty array
function addfile(val) {
if (inclfls.length != 0) {
for (var i = 0; i < inclfls.length; i++) {
if (inclfls[i] == val) {
a.style.background = "#999";
inclfls.splice(i, 1); //remove it
}
else {
a.style.background = "#2ECC71";
inclfls.push(val); //push it
}
}
}
else {
a.style.background = "#2ECC71";
inclfls.push(val);
}
alert(inclfls.length);
}
What am I doing wrong?
with array methods, its much simpler:
function addfile(val) {
var index=inclfls.indexOf(val);
if(index===-1){
inclfls.push(val);
a.style.background = "#999";
}else{
inclfls.splice(index,1);
a.style.background = "#2ECC71";
}
}

How to capture JSON export and send to URL

I added the code you suggested, thanks, but still not seeing anything on the targeted wordpress page- http://rpssolar.com/?page_id=1822. I think I am missing login information= or something else??
This is the code now:
// Includes functions for exporting active sheet or all sheets as JSON object (also Python object syntax compatible).
// Tweak the makePrettyJSON_ function to customize what kind of JSON to export.
var FORMAT_ONELINE = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY = 'Pretty';
var LANGUAGE_JS = 'JavaScript';
var LANGUAGE_PYTHON = 'Python';
var STRUCTURE_LIST = 'List';
var STRUCTURE_HASH = 'Hash (keyed by "id" column)';
/* Defaults for this particular spreadsheet, change as desired */
var DEFAULT_FORMAT = FORMAT_PRETTY;
var DEFAULT_LANGUAGE = LANGUAGE_JS;
var DEFAULT_STRUCTURE = STRUCTURE_LIST;
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{name: "Export JSON for this sheet", functionName: "exportSheet"},
{name: "Export JSON for all sheets", functionName: "exportAllSheets"},
{name: "Configure export", functionName: "exportOptions"},
];
ss.addMenu("Export JSON", menuEntries);
}
function exportOptions() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle('Export JSON');
var grid = app.createGrid(4, 2);
grid.setWidget(0, 0, makeLabel(app, 'Language:'));
grid.setWidget(0, 1, makeListBox(app, 'language', [LANGUAGE_JS, LANGUAGE_PYTHON]));
grid.setWidget(1, 0, makeLabel(app, 'Format:'));
grid.setWidget(1, 1, makeListBox(app, 'format', [FORMAT_PRETTY, FORMAT_MULTILINE, FORMAT_ONELINE]));
grid.setWidget(2, 0, makeLabel(app, 'Structure:'));
grid.setWidget(2, 1, makeListBox(app, 'structure', [STRUCTURE_LIST, STRUCTURE_HASH]));
grid.setWidget(3, 0, makeButton(app, grid, 'Export Active Sheet', 'exportSheet'));
grid.setWidget(3, 1, makeButton(app, grid, 'Export All Sheets', 'exportAllSheets'));
app.add(grid);
doc.show(app);
}
function makeLabel(app, text, id) {
var lb = app.createLabel(text);
if (id) lb.setId(id);
return lb;
}
function makeListBox(app, name, items) {
var listBox = app.createListBox().setId(name).setName(name);
listBox.setVisibleItemCount(1);
var cache = CacheService.getPublicCache();
var selectedValue = cache.get(name);
Logger.log(selectedValue);
for (var i = 0; i < items.length; i++) {
listBox.addItem(items[i]);
if (items[1] == selectedValue) {
listBox.setSelectedIndex(i);
}
}
return listBox;
}
function makeButton(app, parent, name, callback) {
var button = app.createButton(name);
app.add(button);
var handler = app.createServerClickHandler(callback).addCallbackElement(parent);;
button.addClickHandler(handler);
return button;
}
function makeTextBox(app, name) {
var textArea = app.createTextArea().setWidth('100%').setHeight('200px').setId(name).setName(name);
return textArea;
}
function exportAllSheets(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheetsData = {};
for (var i = 0; i < sheets.length; i++) {
var sheet = sheets[i];
var rowsData = getRowsData_(sheet, getExportOptions(e));
var sheetName = sheet.getName();
sheetsData[sheetName] = rowsData;
}
var json = makeJSON_(sheetsData, getExportOptions(e));
return displayText_(json);
}
function exportSheet(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rowsData = getRowsData_(sheet, getExportOptions(e));
var json = makeJSON_(rowsData, getExportOptions(e));
return displayText_(json);
}
function getExportOptions(e) {
var options = {};
options.language = e && e.parameter.language || DEFAULT_LANGUAGE;
options.format = e && e.parameter.format || DEFAULT_FORMAT;
options.structure = e && e.parameter.structure || DEFAULT_STRUCTURE;
var cache = CacheService.getPublicCache();
cache.put('language', options.language);
cache.put('format', options.format);
cache.put('structure', options.structure);
Logger.log(options);
return options;
}
function makeJSON_(object, options) {
if (options.format == FORMAT_PRETTY) {
var jsonString = JSON.stringify(object, null, 4);
} else if (options.format == FORMAT_MULTILINE) {
var jsonString = Utilities.jsonStringify(object);
jsonString = jsonString.replace(/},/gi, '},\n');
jsonString = prettyJSON.replace(/":\[{"/gi, '":\n[{"');
jsonString = prettyJSON.replace(/}\],/gi, '}],\n');
} else {
var jsonString = Utilities.jsonStringify(object);
}
if (options.language == LANGUAGE_PYTHON) {
// add unicode markers
jsonString = jsonString.replace(/"([a-zA-Z]*)":\s+"/gi, '"$1": u"');
}
return jsonString;
}
var JSON_DESTINATION_URL = 'http://rpssolar.com/?page_id=1822';
function sendJson_(json) {
var options = {
"contentType":"application/json",
"method" : "post",
"payload" : json
};
UrlFetchApp.fetch(JSON_DESTINATION_URL, options);
}function displayText_(text) {
var app = UiApp.createApplication().setTitle('Exported JSON');
app.add(makeTextBox(app, 'json'));
app.getElementById('json').setText(text);
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.show(app);
return app;
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData_(sheet, options) {
var headersRange = sheet.getRange(1, 1, sheet.getFrozenRows(), sheet.getMaxColumns());
var headers = headersRange.getValues()[0];
var dataRange = sheet.getRange(sheet.getFrozenRows()+1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
var objects = getObjects_(dataRange.getValues(), normalizeHeaders_(headers));
if (options.structure == STRUCTURE_HASH) {
var objectsById = {};
objects.forEach(function(object) {
objectsById[object.id] = object;
});
return objectsById;
} else {
return objects;
}
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData_(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders_(arrayTranspose_(headersTmp)[0]);
return getObjects(arrayTranspose_(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects_(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty_(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders_(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader_(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader_(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum_(letter)) {
continue;
}
if (key.length == 0 && isDigit_(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty_(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum_(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit_(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit_(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose_(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
Instead of displaying the text via the displayText_() function, define a new function which POSTS the JSON to your destination.
var JSON_DESTINATION_URL = 'http://requestb.in/1gngj131';
function sendJson_(json) {
var options = {
"contentType":"application/json",
"method" : "post",
"payload" : json
};
UrlFetchApp.fetch(JSON_DESTINATION_URL, options);
}
If you still want to see the popup of text, just call this function before you call displayText_().
I'm assuming you want to POST this data. If you want to use another HTTP method, see the "method" section and related examples in the docs:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

User:index is undefined?

I have made a localStorage with a user_name login and i have parsed the string of my JSON data (entry) to a plain object.
But if I try to console log entry.username i get my stored users but also get a "undefined"?
I suspect that is my User:index code that is messing up the entry.user_name?
var User = {
index: window.localStorage.getItem("User:index"),
$form: document.getElementById("userReg"),
$button_register: document.getElementById("registerUser"),
$button_login: document.getElementById("logIN"),
init: function() {
// initialize storage index
if (!User.index) {
window.localStorage.setItem("User:index", User.index = 1);
}
User.$form.addEventListener("submit", function(event) {
var entry = {
id: parseInt(this.id_entry.value),
user_name: this.user_name.value,
};
if (entry.id == 0) {
User.storeAdd(entry);
}
}, true);
User.$button_login.addEventListener("click", function(entry) {
for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i);
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
}
if (document.getElementById("firstName").value == entry.user_name) {
alert("You have logged in");
} else {
document.getElementById("negative").innerHTML = "Username does not match"
}
}, true);
},
storeAdd: function(entry) {
entry.id = User.index;
window.localStorage.setItem("User:index", ++User.index);
window.localStorage.setItem("User:" + entry.id, JSON.stringify(entry));
},
};
User.init();
The issue is the data in localStorage. Your login function assumes that all entries stored in localStorage will be of your User entry type. But when you start storing other things, you have no checking to confirm the type is what you expect.
Here:
for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i);
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
}
The line that is actually failing is: entry = JSON.parse(window.localStorage.getItem(key)); because at the end of the loop, the type in localStorage is User:index, not User:3.
If you plan on having more things in localStorage, you should add a check in your loop, such as this:
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i);
var reg = new RegExp("User\:\\d+$");
//Only process user entries
if(reg.test(key)) {
var value = localStorage[key];
entry = JSON.parse(window.localStorage.getItem(key));
console.log(entry.user_name);
console.log(entry);
} // end if
}
Here is a fiddle: http://jsfiddle.net/xDaevax/Lo63vftt/
Disclaimer: I changed some other things to in order for it to work more efficiently for a fiddle, you can ignore the other changes I made.
You are right it is the User:index causing this issue. You can fix it with the following code.
for(var i = 1; i < User.index; i++) {
var key = "User:" + i;
var entry = JSON.parse(localStorage[key]);
console.log("entry : ", key, entry);
...
http://jsfiddle.net/yv04x4mw/6/
May I also recommend not creating accounts this way (unless you have a good reason), also use a JavaScript library like jQuery.

Categories

Resources