1
It’s very simple what I want to do: In HTML there is a input where the person enters with the information, I pick it up and saved in the localstorage, but localstorage.setIten() it overwrites, so I want to save the information in a array and display on HTML within a li.
Ex: the person enters the input with the information = apple, pineapple, grape
I want to save her in the localstorage thus: Key would be "fruit" and Value would be [apple, pineapple, grape]
I’m sending the code I tried to do but got lost, someone could help me with the easiest way to do it ?.
Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Lista de Compras</h1>
<input type="text" id="input">
<button id="button">Compras</button>
<button id="delete">Deletar</button>
<ul id="lista"></ul>
<script>
const buttton = document.querySelector('#button')
const input = document.querySelector('#input')
const lista = document.querySelector('#lista')
const deletar = document.querySelector('#delete')
let array = []
buttton.addEventListener('click', () => {
array.push(input.value)
localStorage.setItem('compras', JSON.stringify(array))
let aa = JSON.parse(localStorage.getItem('compras'))
aa.map(x => {
return(
lista.innerHTML = `
<li>
${x}
</li>
`
)
})
input.value = ''
})
window.addEventListener('DOMContentLoaded', () =>{
lista.innerHTML = `
<li>
${localStorage.getItem('compras')}
</li>
`
})
deletar.addEventListener('click', () => {
localStorage.clear()
lista.remove()
input.value = ''
})
</script>
</body>
</html>
That’s right, I just think we’re missing a '{element}. innerHTML = ' before the map, and a '.Join("")' after, and instead of the local variable 'aa' use the 'array'.
– anon
I saw they gave a -1, the question got bad personal ? , could not understand. If you can help me, I appreciate.
– daniel
Your question is similar to this: https://answall.com/questions/399129/localstorage-salvar-alguns-campos?rq=1
– LeAndrade
All right Leandrade, I looked before asking the question and it’s not what I want to do, I want to add an array in the Storage location and then read it in html. Thank you
– daniel