简体   繁体   中英

How do I prevent my program from overwriting localStorage every time a button is clicked?

document.getElementById("submit").addEventListener("click", getElements)

function getElements() {

  var a = document.getElementById("sample").value;
  var x = new obj(a);

  function store() {
    localStorage.setItem('todays-values', Object.values(x));
  }

  store();
}

In a separate js file I then call

localStorage.getItem('todays-values');

I get the values, but if I put new inputs into my html file and click the submit button, the previous values get overwritten and replaced by the new ones. How do I store all the values that are submitted and prevent the old ones from getting replaced?

I'm very new to Javascript so I would prefer to solve this problem without the use of any additional libraries if possible.

First: it seems that you are mixing JavaScript a class with a function (here is an example: What techniques can be used to define a class in JavaScript, and what are their trade-offs? )

For example this is the class equivalent in JavaScript:

function ClassName() {
  var privateVar;
  this.publicVar;

  function privateFunction() {}

  this.publicFunction = function() {};
}

You shouldn't wrap a function in a function unless it has a meaning (beacuse it is confusing for other people otherwise), but in the example given you don't need that. Also I can't see the reason why you are creating a new object x - if you create the object right before you save it you could just save the value because the object will only contain the value from sample , so you could write something like this:

document.getElementById("submit").addEventListener("click", getElements);

function storeElements() {
  var sampleValue = document.getElementById("sample").value;
  localStorage.setItem('todays-values', sampleValue);      
}

Back to your question:

As Kalamarico mentioned: if you write new values into todays-values you will overwrite your old values, you could simply load all old values from the localStorage append the new ones and write them back to the localStorage.

You should also note that the localStorage only takes strings, so you should stringify objects (see localStorage.setItem ).

function appendValueToStorage(key, value) {
  var values = JSON.parse(localStorage.getItem(key));
  if (values === null) {
    values = [];
  }

  values.push(value);
  localStorage.setItem(key, JSON.stringify(values));
  console.log(localStorage.getItem(key));
}

appendValueToStorage('todays-values', document.getElementById("sample").value);

The function will let you append some value for a key, you could even wrap this function again to be able to use it in your click function:

function onSubmitClick() {
  appendValueToStorage('todays-values', document.getElementById("sample").value);
}

document.getElementById("submit").addEventListener("click", onSubmitClick);

With the console.log command you can see the current content of the localStorage (you could also check with the developer tools - I find the ones for chrome work the best, under the Application -> Local Storage tab you can check the localStorage of your page).

You need read more about localStorage, this is a new feature introduced with HTML5, you can take a look here and see all features.

localStorage stores your data like a JSON object, if you don't know what is JSON, you need to find info. In javascript think in objects in this way:

var myData = {
  myName: 'Kalamarico',
  myAge: undefined
};

This is a Javascript object, and JSON is very similar and it is a representation of objects. localStorage API stores your data as this way, when you do:

localStorage.setItem('todays-values', Object.values(x))

localStorage saves a new entry, one key 'todays-values' and its value is an object, so, your localStorage seems:

{
  "todays-values": { ... }
}

Every time you set a "todays-values" you will overwrite the key, as you are seeing, so, if you can keep old values, you need to do this manage, first you can get items in localstorage (if there are), and after you can "merge" your old value and the new value. Or you can set a new key, for example: "todays-values1" depends on your need.

If you need to store exactly one key-value pair per day, then you could add the date in the key string.

Else how about numbering the keys (" yourKey_0 ", " yourKey_1 ", ...) and also storing the current (biggest) index (" currentIndex ")in local storage:

function store(value) {
    newIndex = localStorage.getItem("currentIndex") + 1;
    localStorage.setItem("yourKey_" + newIndex, value);
    localStorage.setItem("currentIndex", newIndex);
}

If you run into problems storing integer values, convert to strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM