I'm having issues with the logic of using Local session variables. So I understand that HTML5 allows you to set and get these local storage variables.
I've read through this post: adding objects to array in localStorage
and understood that by using SetItem, you will rewrite the variable that you have set and thus for a dynamic array, you will need to get the variable first before pushing a new value.
So the problem I'm having, and I dont't even know if it's possible, is that I want to have, for example, a index.html page which accepts a user input and adds it into an array that needs to be persistent. When the user reloads the same page, the previous input will still be in the same array. From what I read from the post mentioned previously, you will rewrite the variable if you use SetItem. However, if I don't use setItem, how will I be able to specify that the array is to be a local Storage variable... I'm sorry if I confused anyone... because I am quite confused myself. Thanks in advance.
All of your assumptions are correct. You can only write to localStorage using setItem, and when setItem is called, you overwrite whatever value exist there. Therefore, the only way to add an item to an array in localStorage is to get the array from localStorage, manipulate it and then put it back with the new items.
// Check if we already have an array in local storage.
var x = localStorage.getItem("myArray");
// If not, create the array.
if (x === null) x = [];
// If so, decode the array.
else x = JSON.parse(x);
// Add our new item.
x.push("value 1");
// Encode the array.
x = JSON.stringify(x);
// Add back to LocalStorage.
localStorage.setItem("myArray", x);
This could done by the following approach:
var myInput = document.getElementById("myInput").value; // user data
var myList = JSON.parse(localStorage.getItem("myList")); // retrieve the list from LS
if(!Array.isArray(myList)) { // if LS list is not ok, instantiate new array
myList = [];
}
myList.push(myInput); // append user data to the list
localStorage.setItem("myList", JSON.stringify(myList)); // save the list back to LS
Related
How to retrieve the session values which are stored in the list using javascript?
I used this code to set the session in the controller.
List<test> _test= new List<test>();
if (Session["testsession"] == null)
Session["testsession"] = _test;
I used this code to retrieve the session list values using javascript
var TEST ='#HttpContext.Current.Session["quotesession"]';
but when i debug it the output is in
var TEST ='System.Collections.Generic.List`1[NLG.IMS.Shared.Models.Test]';
Where i went wrong? I need the session values to be retrieved from the list.
I would advise using a strongly typed model and assigning a property to the collection rather than using session, even the ViewBag would be better but if you really must, this is how you could:
You could use the following:
var json = #Html.Raw(Json.Encode(#HttpContext.Current.Session["quotesession"]));
Which would output it as json.
jsFiddle
The above prints out a collection to the console.log.
I know I can create JSON format of data in javascript
data = JSON.parse(localStorage.something);
data[0] == "some data";
But when i try to delete its not working.
delete data[0];
delete data[0] will only delete that item from the data array, which is NOT the localStorage item (since, as you already know, that item is a string).
You have to save your changes. Also I would suggest using data.shift() as per minitech's comment instead of delete - delete is better for object properties, not array indices.
data = JSON.parse(localStorage.something);
data.shift(); // delete data[0] without breaking sequence
localStorage.something = JSON.stringify(data);
After you do:
data = JSON.parse(localStorage.something);
Then the data variable holds an idependent object which from now is completely detached from localStorage (which stores just a String that need to be parsed anyway, not a 'real' object).
If you change it, you need to manually update the local storage like that:
localStorage.setItem("something", JSON.stringify(data));
As a side note: if you are aiming at older browsers, then make sure you include something like json2.js to make JSON object work everywhere.
I'm currently making a Chrome Extension, and I'm at the last stage of it, storing the users preferences.
I know Local Storage will store strings, and at this stage I'm getting awway with just using strings, but as the storage requirements get bigger, a 2 dimentional array is required. I've seen that Local Storage is not capable of storaing an array, but you can use JSON. I've never used JSON, and when looking at examples, I do not understand how to do so.
for (i=1;i<=localStorage["totalwebsites"];i++) {
// Get the title of the current item
var title = localStorage["websitetitle" + i];
// Create the new context menu item, and get its menuItemId to store in the right localStorage string
var menuItemId = chrome.contextMenus.create({parentId: ParentID, title: title, contexts:["selection"], onclick: searchFromContext});
// Store the created menu items menuItemId in the array so we know which item was chosen later on
websitesarray[menuItemId] = localStorage["websiteurl" + i];
}
As you can see, this gets very messy, very quick, when using strings. I was hoping for totalwebsites to become a count of the items in the array, and websitetitle and websiteurl to be in the 2 dimetional array.
I don't see how you would do this in JSON, or at least how this could be permanently stored in Chrome itself. I'm guessing you'd have to convert it back to Local Storage Strings at some point or something? I don't think I'm getting this.
Any help/pointers would be much appreciated, I can't find much :(
Don't worry, JSON is super easy! Assuming that your websites are stored in websitesarray:
// To load:
websitesarray = JSON.parse(localstorage.websites);
// To store:
localstorage.websites = JSON.stringify(websitesarray);
Make sure you have a sane way to handle the case where localstorage.websites isn't set yet, as JSON.parse will throw a fit if its input is empty.
I am using local storage to store user entries and am displaying the entries on another page. I need a way to sort them based on the most recent date and time of edit. Is there a way to do this with HTML5. If not, what's the easiest/most effective way to do so?
Thanks for the inputs.
If your keys/values have an inherent order to them (alphabetical, numerical, etc), then putting a timestamp in them may be superfluous. Although the Storage object has no sort method, you can create a new Array() and then sort that.
function SortLocalStorage(){
if(localStorage.length > 0){
var localStorageArray = new Array();
for (i=0;i<localStorage.length;i++){
localStorageArray[i] = localStorage.key(i)+localStorage.getItem(localStorage.key(i));
}
}
var sortedArray = localStorageArray.sort();
return sortedArray;
}
The disadvantage to this is that the array is not associative, but that is by nature of the JavaScript Array object. The above function solves this by embedding the key name into the value. This way its still in there, and the functions you'd use to display the sorted array can do the footwork of separating the keys from the values.
You've got to pair the timestamp with the stored value somehow, you can create a wrapper object for each value and store the value and the timestamp in a single object. Assuming you have a value myvalue you want to store with reference myref:
var d=new Date();
var storageObject = {};
storageObject.value = myvalue;
storageObject.timestamp = d.getTime();
localStorage.setItem(myref, JSON.stringify(storageObject));
On the other page you then need to rehydrate your objects into an array and implement your compareFunction function.
Your other option would be to use Web SQL Database and Indexed Database API which lets you more naturally store and query this sort of multifaceted info, but you would probably have to create some sort of abstract wrapper to make things work easily cross browser.
I am using Greasemonkey/Tampermonkey to visit pages and make a change to a 100-element table based on what's on the current page.
Short term storage and array manipulation works fine, but I want to store the data permanently. I have tried GM_getValue/GM_setValue, GM_SuperValue, localStorage, and indexedDB, but I am clearly missing something fundamental.
Nothing seems to allow me to write the array into the permanent storage and then read it back into a variable where I can access each element, such that variablename[32] is actually the 32nd element in the table (Well, 33rd if you start counting at zero, which I do).
I need access to the entire 100-element table while the script is running, because I need to output some or all of it on the page itself. In the most basic case, I have a for loop which goes from 0 to 99, printing out the value of variablename[i] each time.
I have no predisposition to any method, I just want the frickin' thing to work in a Greasemonkey/Tampermonkey script.
Towards the top of the script I have this:
for (var i = 0; i <= 99; i++) {
currentData[i] = localStorage.getItem(currentData[i]);
}
The purpose of the above section is to read the 100 entries into the currentData array. That doesn't actually work for me now, probably because I'm not storing things properly in the first place.
In the middle, after modifying one of the elements, I want to replace it by doing this:
localStorage.setItem(
currentData[specificElementToChange], differentStuff);
The purpose of the above is to alter one of the 100 lines of data and store it permanently, so the next time the code at the top is read, it will pull out all 100 entries, with a single element changed by the above line.
That's the general principle.
I can't tell if what I'm doing isn't working because of some security issue with Firefox/Chrome or if what I want to do (permanently storing an array where each time I access a given page, one element changes) is impossible.
It's important that I access the array using the variable[element] format, but beyond that, any way I can store this data and retrieve it simply is fine with me.
I think you're going about this wrong. LocalStorage stores strings so the simplest way to store an array in LocalStorage is to stringify it into JSON and store the JSON. Then, when reading it back, you parse the JSON back into an array.
So, to read it in, you do this:
var currentData = JSON.parse(localStorage.getItem("currentData") || "[]");
To save your data, you do this:
localStorage.setItem("currentData", JSON.stringify(currentData));
Working demo: http://jsfiddle.net/jfriend00/6g5s6k1L/
When doing it this way, currentData is a variable that contains a normal array (after you've read in the data from LocalStorage). You can add items to it with .push(), read items with a numeric index such as:
var lastItem = currentData[currentData.length - 1];
Or, change an item in the array with:
currentData[0] = "newValue";
Of course, it's just a normal array, so you can use any array methods on it.