0

var s = 0;
btn.addEventListener('click', function() {
      var ModelMake = prompt("Enter The Model Make"),
        ModelYear = prompt("Enter The Model Year"),
        Km = prompt("Enter The Amount Of Km"),
        Price = prompt("Enter The Price"),
        Status = prompt("Enter The Car's Status"),
        FinalPrice,
        Details = prompt("Enter the Details");

      localStorage.setItem(s += 1, JSON.stringify({
        ModelMake: ModelMake,
        ModelYear: ModelYear,
        Km: Km,
        Price: Price,
        Status: Status,
        Details: Details,
        FinalPrice: FinalPrice
      }));

How do i avoid having my previous localStorage objects overwritten after the user REFRESHES or CLOSES the browser. The reason i capitalized is to emphasize that this code works and keeps generating different objects by incrementing as long as the user doesn't refresh or close the browser. the moment you refresh or reopen the application then enter new values the previous objects get overwritten with the new ones and the incrementation starts all over from 1 (overwriting the previous 1).

Murad Elboudy
  • 127
  • 2
  • 2
  • 11

2 Answers2

0

You can get the values first on app load and create.

Actually rather than setting it to 0 initially, store that as 'index' in your localstorage. Then you can pick up where you left off

alexrogers
  • 1,514
  • 1
  • 16
  • 27
0

Try this. I've created a new variable index which store the value of s at the end of each run. This value is read while initializing s the next time user opens the page, so that you can continue where you left off.

var s = 0; // Problem lies here
if(typeof(Storage)!=="undefined")
{
    s = parseInt(localStorage.getItem("index"));
}

btn.addEventListener('click', function() {
      var ModelMake = prompt("Enter The Model Make"),
        ModelYear = prompt("Enter The Model Year"),
        Km = prompt("Enter The Amount Of Km"),
        Price = prompt("Enter The Price"),
        Status = prompt("Enter The Car's Status"),
        FinalPrice,
        Details = prompt("Enter the Details");

      localStorage.setItem(s += 1, JSON.stringify({
        ModelMake: ModelMake,
        ModelYear: ModelYear,
        Km: Km,
        Price: Price,
        Status: Status,
        Details: Details,
        FinalPrice: FinalPrice
      }));

     localStorage.setItem('index', s);

});
Playmaker
  • 1,458
  • 1
  • 14
  • 23
  • Unfortunetly it doesn't work i get an error "Unexpected token N" and when i refresh or reopen the browser it only saves one object and deletes the rest – Murad Elboudy Dec 23 '14 at 22:04
  • Try removing the last `});` from my code and paste. It won't be there according to your code. But your code was lacking it, so I added it. – Playmaker Dec 24 '14 at 05:14
  • It finally worked on it's own lol :D without even removing the last '});' , thanks alot man much appreciated. you're a life saver – Murad Elboudy Dec 24 '14 at 20:59