luistavares

JavaScript - Como armazenar vários dados (array) no localStorage

May 30th, 2022 (edited)
1,082
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2.    <head>
  3.       <title>JavaScript Array</title>
  4.       <style>
  5.          #d {
  6.             width: 500px;
  7.             min-height: 100px;
  8.             border: 1px dashed black;
  9.          }
  10.       </style>
  11.       <script>
  12.         var arr = [];
  13.  
  14.         function addItem(){
  15.            if (localStorage.meuArr){             
  16.               arr = JSON.parse(localStorage.getItem('meuArr'));
  17.            }
  18.            
  19.            let novoItem = document.getElementById("v").value;
  20.            arr.push(novoItem);
  21.            document.getElementById("v").value = "";
  22.            localStorage.meuArr = JSON.stringify(arr);
  23.         }
  24.  
  25.         function showItems(){
  26.            let resultDIV = document.getElementById('d');
  27.            resultDIV.innerHTML = "";
  28.            if (localStorage.meuArr){             
  29.               arr = JSON.parse(localStorage.getItem('meuArr'));
  30.            }
  31.            
  32.            for(var i in arr){
  33.               let p = document.createElement("p");
  34.               p.innerHTML = arr[i];
  35.               resultDIV.append(p);
  36.            }
  37.         }
  38.  
  39.         function clearItems(){
  40.            arr = [];
  41.            localStorage.meuArr = JSON.stringify(arr);  
  42.         }
  43.       </script>
  44.    </head>
  45. <body>
  46.    <h3>Array com JavaScript</h3>
  47.    <label>Informe valor: </label>
  48.    <input id="v" /><br>
  49.    <button onclick="addItem()">Add</button><br>
  50.    <button onclick="showItems()">Show</button><br>
  51.    <button onclick="clearItems()">Clear</button><br>
  52.    <div id="d"></div>
  53. </body>
  54. </html>
  55.  
Add Comment
Please, Sign In to add comment