JQuery Mobile JSON Stringify - javascript

I'm new in jquery mobile. I'm doing a shopping list application for my school assignment and I'm requested to store objects in local storage.
Each item must include the following information: item Name, item quantity and a Boolean is_bought.
I wish to store all items data into one JSON string. Items data is entered by user from an other page.
My problem is
1)How items can be stored in local storage through JSON stringify.
2)How items data can be retrieved from JSON string to be represented into a list.

First: If I understood you right you have an object(json) structure like:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
If not (in question you have no key(name) for your variables) your structure must be like I showed for having an access to each variable in the object.
Second: About localStorage. It is limited to handle only string key/value pairs, so you can't just save an object in it. You have to use JSON.stringify() to parse your object into the string and save in localStorage, then, after retrieving, use JSON.parse() to parse it back. The code could look like this:
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT: TO STORE MULTIPLE ITEMS
So, if your question is about storing multiple items and distinguishing them, and if your item's name is unique and you know what item is bought, you can store them into the localStorage with the key of item's name, e.g.
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));

Related

LocalStorage not keeping values

I have a form that whenever I add info it should keep it in localStorage so I cant then retrive it from a global variable.
But on refresh it only gives back the last input I did and its not really storing anything.
help please
let todoList = [localStorage.getItem("list")] || [];
newTask.addEventListener("submit", addList)
function addList(e){
e.preventDefault();
let input = document.querySelector(".new-list input")
newListName = input.value;
input.value = ""
newTaskList.push(newListName)
//todoList.push(newListName)
localStorage.setItem("list", newListName);
}
Storing Your Array as a String
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
Notice that my data is being stored under the key called quentinTarantino.
Retrieving Your Data
Storing your data is only part of the fun. A very important part of all this is being able to retrieve your data and get back to using it like an array. This involves first retrieving your data as a string:
var retrievedData = localStorage.getItem("quentinTarantino");
My retrievedData variable is storing the values returned by my local storage item whose key is quentinTarantino. This data is currently in the form of a string.
To convert from a string back to an object, use the JSON parse function:
var movies2 = JSON.parse(retrievedData);
Once you have done this, the movies2 variable will point to the parsed data which is, as you can guess, an array. You can call all of the array methods on your movies2 Array object just like you always would for any old array.

Javascript localstorage get the value into array one by one

Problem:
I would like get the localstorage value "car", i want to get the result like car = ["red","blue"] in other page, i want to get the result into array one by one. How can i fix it?
page 1:
car = ["red","blue"];
localStorage.setItem("car", JSON.stringify(car));
Another Page:
var car1 = JSON.parse(localStorage.getItem("car"));
alert(car1[0])
****show two record at the same time , i want to put it into array like car1[0] = red; car1[1] = blue;
as i know, when you convert it to json it wouldn't parse to you items like array
so car[0] doesn't work as you want,
This is a good resource of using localstorage:
https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/
U must enter the items as an object and give them an id
like this:
{
name: red,
id: 1,
}
Then retrieve it by car id.
and a better answer: How do I store an array in localStorage?
And know it JSON is not supported in IE7 and earlier.

Parsing retrieved localStorage item brings undesired result in console

I am making a note web app using localStorage, when user submits a note, the values from the input and textarea are saved in a object.
Each note created is a object containing key/value pairs
id: 0
title: value from input
content: value from textarea
After localStorage contains least one item with a string from then on in when a new note is created, I get/retrieve the localStorage string which will contain past entered notes in string format.
Parse the localStorage string and save it into a variable/array to have the prior notes to add on to.
Push new input values saved into input object each time, to the array before setting the localStorage item with the array(stringifying it of course).
Below is the function that's responsible for saving the note into localStorage
// User clicks to save note
post_note_button.onclick = function() {
// Get values from input and textarea
var note_title = document.getElementById("note-title").value;
var note_textarea = document.getElementById("note-textarea").value;
// Each time note is created, new values from input will be saved
var input = { id: note_id_count, title: note_title, content: note_textarea };
// ------------------------------------------------
switch(localStorage.getItem("note")) {
// If retrieve for localStorage item returns false/doesn't exist
// PURPOSE: Set localStorage string for first time
// 1. Create localStorage item with values from user's input
case null:
localStorage.setItem("note", JSON.stringify(input));
break;
// If retrieve for localStorage item returns true/exists
// PURPOSE: To retrieve localStorage string and manipulate it
// 1. Changing localStorage string, requires string to be retrieved and saved as array
// 2. Add item to array
// 3. Create/set localStorage item with values from array, convert to string
default:
var note_array = [JSON.parse(localStorage.getItem("note"))];
console.log(note_array);
note_array.push(input);
localStorage.setItem("note", JSON.stringify(note_array));
break;
}
// ------------------------------------------------
};
MY PROBLEM:
When I console.log & parse the localStorage item "note" after adding a few notes, I should get
Array [ Object, Object, Object ]
instead I get:
Array [ Array[2], Object ]
codepen: http://codepen.io/anon/pen/JdjMYq
It looks like when you save the first item into the localStorage (when there is nothing there), you are just saving it as an object. Then when you add the next item, you wrap it in an array.
Instead you could save the original object wrapped in an array, and then just push onto that one:
case null:
localStorage.setItem("note", JSON.stringify([input]));
break;
--
default:
var note_array = JSON.parse(localStorage.getItem("note"));
console.log(note_array);
note_array.push(input);
localStorage.setItem("note", JSON.stringify(note_array));
break;
See this forked codepen

In localStorage how do we save similar tuples with index?

In our extension, we are getting values of username( eg: Johnny123), accname (eg: Facebook).
I want to store this for multiple accounts and usernames in the localStorage.
We have written this code :
var i = Number(localStorage.usercounter); // counter for number of users
localStorage.username(i) = username.value; // textbox value
localStorage.accname(i) = accname.value; // textbox value
this code is not executing, what is the right way to store the values?
localStorage.username = username.value;
localStorage.accname = accname.value;
this is executing and allowing us to retrieve values. Please Help.
localStorage stores strings on data-properties...
...your options are:
store a JSON representation of an array which contains user objects
var userdata = [{ name : "Bob", account : "Facebook" },
{ name : "Doug", account : "LinkedIn" }],
userjson = JSON.stringify(userdata);
localStorage.setItem("users", userjson);
console.log(JSON.parse(localStorage.getItem("users")[0].name);
store a JSON/string representation to a suffixed key
localStorage.setItem("user_0_name", "Bob" );
localStorage.setItem("user_0_account", "Tumblr");
localStorage.setItem("user_1_name", "Doug" );
localStorage.setItem("user_1_account", "MySpace");
// ...
As you can see, the first option is the one that makes more sense.
This is how I'd read write it using truStorage (https://github.com/andresgallo/truStorage)
truStorage.setItem('a',{});//This will be the main key, the one localStorage is aware of
truStorage.setItem('a.b',[1,2,3]);//Now we can store variable 'b' inside object a
truStorage.getItem('a'); //returns entire object {a : {b: [1,2,3]}}
truStorage.getItem('a.b') //returns child object {b: [1,2,3]}
You can write directly to child items the same way as you suggested.
truStorage.setItem('a.b.c', 'value of third level nested object c');
In the background this really does the JSON parse/stringify and recursion for you, which will clean up you application massively if you are using lots of localStorage.

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources