-1
Hello, I want to store some data in the localStorage, but when I reload the page the data recovers in a messy way, also showing the information [Object Htmlinputelement]. You understand where I’m going wrong?
Here a fiddle: https://jsfiddle.net/9rjLo73z/
Here the code, if you prefer:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mydiv {
background-color: green;
}
.mydiv2 {
background-color: orange;
}
</style>
</head>
<body>
<div class="small-container">
<h1>Dados</h1>
<form>
<input id="item" type="text" placeholder="dado"><br>
<input id="item2" type="text" placeholder="dado1">
<input type="button" value="create" onclick="create()">
</form>
<h2>Items</h2>
<section></section>
<button>Limpar</button>
</div>
<script>
const form = document.querySelector('form');
const section = document.querySelector('section');
const button = document.querySelector('button');
const input = document.getElementById('item');
const input2 = document.getElementById('item2');
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
const divMaker = (text) => {
const div = document.createElement('div');
div.setAttribute('class', 'mydiv')
div.textContent = text;
section.appendChild(div);
}
const divMaker2 = (text) => {
const div2 = document.createElement('div');
div2.setAttribute('class', 'mydiv2')
div2.textContent = text;
section.appendChild(div2);
}
function create() {
itemsArray.push(input.value);
itemsArray.push(input2.value);
localStorage.setItem('items', JSON.stringify(itemsArray));
divMaker(input.value);
divMaker2(input2.value);
input.value = "";
input2.value = "";
};
data.forEach(item => {
divMaker(item);
divMaker2(item2);
});
button.addEventListener('click', function () {
localStorage.clear();
while (section.firstChild) {
section.removeChild(section.firstChild);
}
itemsArray = [];
});
</script>
</body>
</html>
My dear, thank you very much! I will analyze to the maximum your example to understand well the logic. Hug!!
– Thiago Soubra