youngmago
youngmago

Reputation: 57

How to clear localStorage on button click

I followed a tutorial on Youtube about localStorage and everything went fine. After that I tried to mess around with the concepts and wanted to add a button to remove the localStorage (id ="btnClear").

Now I've tried everything but it doesnt let me remove the storage. I think its because I declared the constants inside the function and I might have to store them somewhere outside and stringify the input. But can I clear the localStorage somehow even in this scenario?

<body>
<content>
      <fieldset>
        <legend>Insert Data</legend>
        <input type="text" id="inpKey" placeholder="Insert Key.." />
        <input type="text" id="inpValue" placeholder="Insert Value.." />
        <button type="button" id="btnInsert">Insert</button>
      </fieldset>
      <fieldset>
        <legend>Local Storage</legend>
        <div id="lsOutput"></div>
        <br />
        <button type="button" id="btnClear">Clear</button>
      </fieldset>
    </content>
  </body>
  <script type="text/javascript">
    const inpKey = document.getElementById("inpKey");
    const inpValue = document.getElementById("inpValue");
    const btnInsert = document.getElementById("btnInsert");
    const lsOutput = document.getElementById("lsOutput");
    const btnClear = document.getElementById("btnClear");

    btnInsert.onclick = function () {
      const key = inpKey.value;
      const value = inpValue.value;

      if (key && value) {
        localStorage.setItem(key, value);
        location.reload();
      }
    };

    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      const value = localStorage.getItem(key);
      lsOutput.innerHTML += `${key}: ${value}`;
    }

    //BUTTON CLEAR

    btnClear.onclick = function () {
      localStorage.clear();
    };
  </script>

Upvotes: 1

Views: 1795

Answers (2)

Utmost Creator
Utmost Creator

Reputation: 1121

Have a look here, I have update all you code from HTML to JS.

You can test it on jsfiddle as stackoverflow will throw this error:

{
  "message": "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.",
  "filename": "https://stacksnippets.net/js",
  "lineno": 37,
  "colno": 33
}

Also, It is better to use document.addEventListener with most of your events (as they provide you with reacher experience)

See more on events here A quote from this URL:

The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[doc], meaning that it can be overwritten.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>How to clear localStorage on button click</title>
</head>

<body>

    <content>
        <fieldset>
            <legend>Insert Data</legend>
            <input type="text" id="inpKey" placeholder="Insert Key.." />
            <input type="text" id="inpValue" placeholder="Insert Value.." />
            <button type="button" id="btnInsert">Insert</button>
        </fieldset>
        <fieldset>
            <legend>Local Storage</legend>
            <ul id="outputList"></ul>
            <br />
            <button type="button" id="btnClear">Clear</button>
        </fieldset>
    </content>

    <script type="text/javascript">
        const printLSContent = function (el) {
            for (let i = 0; i < localStorage.length; i++) {
                let key = localStorage.key(i);
                let value = localStorage.getItem(key);
                let li = document.createElement('li');
                li.innerHTML = `K: ${key}; V: ${value}`;
                el.appendChild(li);
            }
        }
        document.addEventListener("DOMContentLoaded", function (event) {
            const inpKey = document.getElementById("inpKey");
            const inpValue = document.getElementById("inpValue");
            const btnInsert = document.getElementById("btnInsert");
            const outputList = document.getElementById("outputList");
            const btnClear = document.getElementById("btnClear");
            // element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
            btnInsert.addEventListener('click', function () {
                const key = inpKey.value;
                const value = inpValue.value;
                localStorage.setItem(key, value);
                location.reload();
            }, false);
            printLSContent(outputList);

            // //BUTTON CLEAR
            btnClear.addEventListener('click', function () {
                localStorage.clear();
                location.reload();
            }, false);
        });
    </script>
</body>

</html>

Upvotes: 0

Lars Flieger
Lars Flieger

Reputation: 2534

Check your local storage in the browser. Your code actually does clear the localStorage. What you are missing is to update your UI. Replace your Button clear code with that:

btnClear.onclick = function () {
   localStorage.clear();
   if(localStorage.length === 0)
      lsOutput.innerHTML = "";
};

Here is a tutorial how you check your local storage in chrome for example: How to view or edit localStorage

Upvotes: 2

Related Questions