How to write localStorage script which will remember the value of turning odometer...so that each time the user visits the site again , the odometer will resume on the value on which odometer was at when the user left the site? I'm beginner in javascript so please understand...
This is my code: https://jsfiddle.net/aht87opr/17/
I've found the following code which might help with my case: http://jsfiddle.net/Jonathan_Ironman/Hn7jc/
$('button').click(function() {
var mefedron = myOdometer.get();
$('#value').text(mefedron);
});
Nicely done on the odometer, looks good. Local storage is simple.
To set local storage:
localStorage.setItem("key", "value");
To get local storage:
var number = localStorage.getItem("key");
Be sure to try getting the local storage first so you can handle any null errors.
Get and Set
localStorage has a few ways to get and set values to the browser. The simplest is treating it like a regular object.
localStorage.distance = 55;
you can then retrieve the value by accessing the property name you created earlier.
console.log(localStorage.distance); // "55"
Strings are stored, parse the string
Notice that localStorage.distance was set as a number but when accessed was a string. If you only need to store a number you could pass the string through a function like parseInt().
console.log(parseInt(localStorage.distance)); // 55
Another solution is to use JSON
create an object model of your odometer.
var odometer = { distance: 55, timeForOilChange: false };
Then write to the localStorage passing your model through JSON.stringify
localStorage.odometer = JSON.stringify(odometer);
and read the value back out using JSON.parse
console.log(JSON.parse(localStorage.odometer));
// { distance: 55, timeForOilChange: false }
Related
I have a SessionStorage item set with the following values:
key : state-allRequestsandResponses
value : "{"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}"
I want to obtain the value for first for example and change the value of 30 to say 40.
I'm having real difficulty with using sessionStorage.setItem to change this value. Can anybody give an example of how to change this value.
You can try below method in order to store, get the data and update
let data = {"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}
//storing the data for the first time
sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
In order to update the data in sessionStorage get the object and parse it as json object since sessionStorage will store the data as strings.
//Get the object and parse it
data = JSON.parse(sessionStorage.getItem("state-allRequestsandResponses"))
data.first = 40;
sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
//Verify whether the data updated in sessionStorage
console.log(sessionStorage.getItem("state-allRequestsandResponses"))
Once we get the value from sessionStorage, we need convert it into JSON in order to use it as a normal object.
try to do some changes like below..
const modifiedValue = JSON.parse(sessionStorage.getItem('state-allRequestsandResponses'));
modifiedValue.first(40);
sessionStorage.setItem('state-allRequestsandResponses', JSON.stringify(modifiedValue));
Hope this helps.. :)
I have an array filled with latitude and longitude pairs pushed like this
doneDotsA.push(lat+"|"+lon);
the values can look like 51.5 or -0.11666666666666667, etc.
then the array is stored in a cookie as an array.
when I try to read the cookie contents it looks like this when In examine it
alert('doneDotsA='+doneDotsA.toString());
yields results like this:
doneDotsA=51.5|-0.11666666666666667
so far so good. however when I try to extract the values like this
for (var t = 0; t < doneDotsA.length; t++) {
alert('val='+doneDotsA[t]);
}
the alert shows 'val=5' then 'val=1' then 'val=.' then 'val=5' etc. somehow reading only one character at a time instead of returning the full number as I'd expect it to do.
does saving an array into a cookie do something to the numbers?
any ideas?
stored in a cookie as an array
Cookies are always stored and retrieved as a string, unless you use custom code to rebuild it into an array after the fact.
A solution like this could be to take your latitude and longitude and put them into a JSON object for serialization and storage in the cookie. Then you can parse them into objects when the site loads.
var coords = {
points:[
{lat:12.4444446,lon:44.55555},
{lat:12.4444446,lon:44.55555}
]
};
var serialized = JSON.stringify(coords);
toStore(serialized);
Then you can just set it to local store or to anyplace you can store a string.
var myLoaded = fromStore();
var coords = JSON.parse(myLoaded);
coords.points.each(function(coord) {
// do something with points.
});
You should then be able to do something with the points you saved.
One note: you might want to check that myLoaded is not an empty string or wrap parse in a try/catch block. A poorly formed structure will throw an exception.
I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.
From what i understand, i'll have to save the array as a JSON file and then save that locally using HTML5 local storage. Does anyone have any examples so i can get my head around it. The tutorial showing up from Google don't seem very clear.
It can be quite straight-forward. Just put a delegate between your code and localStorage that converts all values from and to JSON:
// conversion functions
var fromJSON = JSON.parse,
toJSON = JSON.stringify;
// storage functions
var get = function(key) {
return fromJSON(localStorage[key]);
};
var set = function(key, value) {
localStorage[key] = toJSON(value);
};
Try CarboStorage. It handles objects automatically, including dates. Filtering is also supported.
http://carbogrid.com/index.php/storage/home
Is it possible that the same name used can have many different values stored separately and to be shown in a list?
E.g.:
function save()
{
var inputfield = document.getElementById('field').innerHTML;
localStorage['justified'] = inputfield;
}
<input type="text" id="field" onclick="save();" />
Every time someone enters something in the input field, and click on save, the localstorage will only save the value in the same name, however, does this conflict the way storage are saved, like being replaced with the latest input value?
Also, is there any way to prevent clearing the localstorage when clearing the cache?
Actually localStorage 'should' be capable of storing integers, strings and arrays. I have been working on a notepad app using localStorage and save all my data using object literals:
var someData = {
withvars: "and values",
init: function() {
// not sure if this works but it should.
},
var1: {
subvar1: "data",
subvar2: "data2"
}
};
Then store it using JSON.stringify():
localStorage.setItem(varName, JSON.stringify(someData));
Then access it later with JSON.parse():
var dataBack = JSON.parse(localStorage.getItem("varName"));
If you always use object literals then you will have less trouble keeping track of how to store and how to retrieve data from localStorage.
No. You can store only one value in a localStorage entry.
There are two ways to store more values behind one keyword:
Use localStorage['justified_0'], localStorage['justified_1'] etcetera.
Store multiple values in an array and convert it to JSON before storing in localStorage['justified'] and convert it back to an array after reading.
Clearing the cache does not clear local storage.
This is something quite easily determined with a very simple test page. You can only store one value per key, and the values are not cleared when the cache is cleared. (I've just tried Firefox so far ...)
You can store a list of values in a single key by writing your own function to do it:
function addToPersistentList(listName, value) {
var val = localStorage[listName] || [];
val.push(value);
localStorage[listName] = val; // THIS DOES NOT WORK
}
edit oops it only supports stored strings; crap. OK well if you have json2 you'd do this:
function addToPersistentList(listName, value) {
var val = localStorage[listName] ? JSON.parse(localStorage[listName]) : [];
val.push(value.toString());
localStorage[listName] = JSON.stringify(val);
}
Of course this causes issues if you want to store dates etc.