i want to be able to remember all values in an array using cookies, but do not know how. I am also using js-cookies.
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
As mentioned, localStorage is a better place to store this data, but using cookies follows the same steps, just need to get a set/get method for Cookies. First you need to see if there is a value. If there is you need to parse it. After you update the array, you need to convert the value to a string and store it.
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());
Related
I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;
I have built a page fiddle, Now I want to store the values entered in the input to window.localStorage. Please help me doing the same.
localStorage can only store strings. Because you want to store all the items added to localStorage you will have to make a string from your list and every time, get the existing list, append, and then re-stringify. Inside your addItem click function
var names = localStorage.getItem('name');
var descriptions = localStorage.getItem('description');
if (names == null) {
localStorage.setItem('name', JSON.stringify([$('.item:last input[name*="-name"]').val()]));
localStorage.setItem('description', JSON.stringify([$('.item:last input[name*="-description"]').val()]));
} else {
names = JSON.parse(names);
descriptions = JSON.parse(descriptions);
names.push($('.item:last input[name*="-name"]').val());
descriptions.push($('.item:last input[name*="-description"]').val());
localStorage.setItem('name', JSON.stringify(names));
localStorage.setItem('description', JSON.stringify(descriptions));
}
JSON.stringify will make your list into a string to put into storage, and JSON.parse will create a list from your string from storage so you can edit the list.
So say I do a query on Parse database and get a results object, with each result having a field place_id.
How can I then get a specific object by place_id from the results without actually going back to the database (want to minimise network traffic and db querying...)?
This is what my query will look like:
var LatestUpdate = Parse.Object.extend("LatestUpdate");
var query = new Parse.Query(LatestUpdate);
query.containedIn("place_id", arrayOfplaceIds);
query.find().then(
function(results){
// and then i want to do something like:
return results.findByField("place_id", 1234) // get a specific object from the result without going back to the database?
}
);
You have to loop through your results and find the object that matches your criteria. You can do this easily using underscore.js which is supported on the cloud:
var match = _.find(results, function(object){ return object.get("place_id") == 1234; });
Just make sure your have var _ = require('underscore'); on top of your js file.
This is my code:
// store item
localStorage.setItem("blog_key", "value I am storing");
// retrieve item
var data = localStorage.getItem("blog_key");
I'm trying to make it list of array for the post, so when somenone click post, it will serve as blog post
Not sure if I got your question or not but I guess you want to do something like this:
// retrieve the local storage value or "[]" and then parse it
var data = JSON.parse(localStorage.getItem("blog_key") || "[]");
// add new item to the array - might want to make sure that the array wont grow too big
data.push("something new");
// store item as string
localStorage.setItem("blog_key", JSON.stringify(data));
I might be wrong though, but that's what I got from your question.
Im using chkArray.push($(this).val()); and document.cookie = 'ids='+chkArray; within a $('input[type=checkbox]:checked').each(function() to store checkboxes values. Then with a simple onclick function (AJAX) fecth products info from db and display in a div.
So far it is working well, but :
How can I reset / Delete the {name:values} created with document.cookie after the onlick event ?
I tried document.cookie.length = 0; and chkArray.length = 0; but it is not working.
How to call the Array with the ids/values ? When I use the debugging console in chrome I can see under cookies Name(ids) and values ( XXX,XXX )
If I want to store different values within the same function using document.coolie, will it replace the first pair (key:value) created from the checkboxes or added to it?
var x = 'abcd'; document.cookie = 'XName='+x;
thanks
You can reset all cookies with document.cookie = ''. You can empty an array with chkArray = []
The cookie format is a key-value pair. For example, document.cookie = 'ids=hi; name=Han'. Now you have a cookie with two key-value pairs. ids and name.
You have to loop yourself to get values out the array. You can use array.join(','). You get a comma seperated list of ids
Since you are already using jQuery, you can have a look at this plugin : jquery-cookie to help you with your problems.