Question

I am trying to build a registration form and using localstorage to save the details. while adding another form details to the locastorage, I want to know what is the value of last inserted key so that I can increment it and can insert new record with incremented value of key.

How it can be done. My current code is overwriting the values if I delete any record, since I am taking count of keys available in storage.

      function setlocal(){
      var o = {};
      var ff = $('#myform').serializeArray();

      $.each(ff, function() {
          if (o[this.name] !== undefined) {
              if (!o[this.name].push) {
                  o[this.name] = [o[this.name]];
              }
              o[this.name].push(this.value || '');
          } else {
              o[this.name] = this.value || '';
          }
      });
      var tt = JSON.stringify(o);
      localStorage.setItem(localStorage.length+1, tt);
      $('#afterInsert').text('data added sucessfully');
      return true;
  }

any suggestions?

Était-ce utile?

La solution

Why can't you store the last inserted key in a separate property

var lastKey = parseInt(localStorage.getItem('lastKey'));
var newKey = lastKey + 1 || 1;
localStorage.setItem(newKey , tt);
localStorage.setItem('lastKey', newKey);

Autres conseils

This should work:

var largestKey = Object.keys(localStorage)
  .filter(isFinite)
  .reduce(function(a, b) {
    return Math.max(a, b);
  }, 0);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top