Click here to Skip to main content
15,923,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!I am creating a coins variable where you can buy pokemon. Each time you buy pokemon, the coins variable will be depleted. How do I make it to where LocalStorage saves my code? I have already tried this code:

function buymagikarp() {
  if(coins >= 100 ) {
    swal("Success", "You bought 1 magikarp!", "success");
    coins -= 100;
    pokemonchosen.push("Magikarp");
    document.getElementById("p1").innerHTML = "Coins: " + coins; 
    coins = localStorage.getItem('coins');
  } else {
    swal("Error", "Not enough balance", "error");
  }
}


What I have tried:

function buymagikarp() {
  if(coins >= 100 ) {
    swal("Success", "You bought 1 magikarp!", "success");
    coins -= 100;
    pokemonchosen.push("Magikarp");
    document.getElementById("p1").innerHTML = "Coins: " + coins; 
    coins = localStorage.getItem('coins');
  } else {
    swal("Error", "Not enough balance", "error");
  }
}
Posted
Updated 1-Aug-17 19:10pm
Comments
Afzaal Ahmad Zeeshan 1-Aug-17 19:09pm    
Where are those objects coming from? pokemonchosen? You are also not setting the object at all, so how would JavaScript know what to do?
Member 13257242 2-Aug-17 13:41pm    
I omitted code from the question that I thought was not needed.

1 solution

You have this line of code:
JavaScript
coins = localStorage.getItem('coins');
You don't want this line. What it does, is overwriting coins after coins -= 100 with the old value from localStorage. You probably want this instead of getItem:
JavaScript
localStorage.setItem('coins', coins);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900