const formulario = document.getElementById("formulario")
const itens = JSON.parse(localStorage.getItem("itens")) || []
itens.forEach((elemento)=>
{
elementCreate(elemento)
})
formulario.addEventListener("submit", (event)=>{
event.preventDefault()
const elName = event.target.elements['elName']
const elQtd = event.target.elements['elQtd']
const isExist = itens.find(f=>f.elName === elName.value)
const itemAtual = {
"elName": elName.value,
"elQtd": elQtd.value
}
if (isExist) {
itemAtual.id = isExist.id
elementUpdate(itemAtual)
itens[isExist.id] = itemAtual
} else {
itemAtual.id = itens.length
elementCreate(itemAtual)
itens.push(itemAtual)
}
localStorage.setItem("itens", JSON.stringify(itens))
elName.value = ""
elQtd.value = ""
})
function elementCreate(item) {
const elNewItem = document.createElement('li')
elNewItem.classList.add("item")
const qtdItem = document.createElement('strong')
qtdItem.innerHTML = item.elQtd
qtdItem.dataset.id = item.id
elNewItem.appendChild(qtdItem)
elNewItem.innerHTML += item.elName
const list = document.getElementById("lista")
list.appendChild(elNewItem)
}
function elementUpdate(item){
document.querySelector("[data-id='"+item.id+"']").innerHTML = item.elQtd
}