0

In my Web university course there is this example with local storage and it says it should show in the input area the number of clicks on the button and also store it in localstorage, but all I get is NaN on the input no matter how many times I click on the button.

<head>
    <script>
        window.onload = function()
        {
        var el=document.getElementById("bt");
        el.onclick= function()
        {
        var x = parseInt(localStorage.getItem("nrc"));
        if (x!==NaN){
        localStorage.setItem("nrc", x + 1);
        }
        else{
        localStorage.setItem("nrc", "1");
        }
        document.getElementById("write").value = localStorage.getItem("nrc");
        }
            document.getElementById("write").value = localStorage.getItem("nrc");
var buton2=document.getElementById("bt2");
        buton2.onlick = function ()
        {
            localStorage.removeItem("nrc");
        }
            }
            </script>
    </head>


    <body>
        <p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
        <button id="bt"> Click</button>
    <button id="bt2"> Click2</button>
    </body>

Edit: problem was solved, but now if i want to remove an item from local storage or clear the localstorage it doesn't work.

2 Answers2

0

You were checking a non number to a non number which will always true.

Anyways the solution is already posted in the comments

<head>
  <script>
    window.onload = function() {
      var el = document.getElementById("bt");
      el.onclick = function() {
        var x = parseInt(localStorage.getItem("nrc"));
        if (!isNaN(x)) {
          localStorage.setItem("nrc", x + 1);
        } else {
          localStorage.setItem("nrc", "1");
        }
        document.getElementById("write").value = localStorage.getItem("nrc");
      }
      document.getElementById("write").value = localStorage.getItem("nrc");
    }
  </script>
</head>


<body>
  <p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
  <button id="bt"> Click</button>
</body>
Rohit.007
  • 3,414
  • 2
  • 21
  • 33
  • Also, I just tried to clear the local storage and it doesn't work, then tried to remove just an item from local storage and it didn't work either. – Alin Catalin Preda Jan 17 '20 at 15:37
0

You have a typo, you wrote onlick instead of onclick

buton2.onclick = function() {
  console.log('clearing storage!');
  localStorage.removeItem("nrc");
  // Reset input back to zero
  document.getElementById("write").value = '0';
}

Complete working example here

Juan Marco
  • 3,081
  • 2
  • 28
  • 32