Reputation: 18278
I try to create a if ... then...
function to push objects into wished localStorage. However, the simple function to push objects into the wished localStorage fails. In localStorage.mydata the parameter mydata is considered as a variable.
JS such:
function pushToLocalStorage(mydata, num) {
localStorage.mydata = num ;
}
pushToLocalStorage("data", 42);
pushToLocalStorage("data2.name", "Hello!");
But I indeed wish to push my values into localStorage.data and localStorage.data2.name.
How to make a function pushing input into a specified localStorage.specificName ?
Upvotes: 3
Views: 85
Reputation: 104785
You can do:
function pushToLocalStorage(mydata, num) {
localStorage.setItem(mydata, num);
}
Retrieve with localStorage.getItem(mydata);
<--- Replace mydata with key name.
Demo: http://jsfiddle.net/wazHr/3/
Also, if you haven't already, be sure to check if the browser even supports localStorage.
Upvotes: 2
Reputation: 3215
Replace localStorage.mydata
by localStorage[mydata] and it works:
function pushToLocalStorage(mydata, num) {
localStorage[mydata] = num ;
}
pushToLocalStorage("data", 42)
Upvotes: 4