(Edited) I'm fairly new to JS and I'm trying to figure out why I can't save these Created Elements into localStorage. What I've tried to do is localStorage.setItem("data", incomeContainer.innerHTML) which from what I understand, should update and save the innerHTMl of incomeContainer every time something changes within it but I can't seem to save the input values when someone adds something. Could anyone help me understand why that is and how I should go about it? I've cut out most of the code to keep it as simple as possible.
let incomeContainer = document.querySelector('#inc');
function userInput() {
addInfo.forEach(btn => {
btn.addEventListener('click', (e) => {
let data = e.currentTarget.dataset.add;
if (data === "income") {
addIncome();
netWorth();
};
})
})
}
function addIncome() {
if (incomeName.value !== "" && incomeAmount.value !== "") {
let trackedDiv = document.createElement('div');
let inputName = document.createElement('input');
let inputAmount = document.createElement('input');
let btnDiv = document.createElement('div');
let editBtn = document.createElement('button');
let checkBtn = document.createElement('button');
let deleteBtn = document.createElement('button');
trackedDiv.classList.add('tracked');
inputName.classList.add('track_name');
inputName.type = "text";
inputAmount.classList.add('track_amount');
inputAmount.type = "number";
btnDiv.classList.add('btn_div');
editBtn.classList.add('edit_item');
checkBtn.classList.add('check_item');
deleteBtn.classList.add('delete_item');
editBtn.innerHTML = `<i class="fa-solid fa-pen-to-square"></i>`;
checkBtn.innerHTML = `<i class="fa-solid fa-check"></i>`;
deleteBtn.innerHTML = `<i class="fa-solid fa-trash"></i>`;
inputName.disabled = "disabled";
inputAmount.disabled = "disabled";
inputName.value = incomeName.value;
inputAmount.value = incomeAmount.value;
incCounter += parseFloat(inputAmount.value);
let convertedIncome = new Intl.NumberFormat('en-US', {style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 2}).format(incCounter);
incomeTotal.innerText = convertedIncome;
trackedDiv.appendChild(inputName);
trackedDiv.appendChild(inputAmount);
btnDiv.appendChild(editBtn);
btnDiv.appendChild(checkBtn);
btnDiv.appendChild(deleteBtn);
trackedDiv.appendChild(btnDiv);
incomeContainer.appendChild(trackedDiv);
incomeName.value = "";
incomeAmount.value = "";
} else {
alert("Missing Income Info!");
}
}
Your code is too long and includes unnecessary stuff, CSS is not necessary to use localStorage.
As for how to use localStorage
localStorage is key-value storage and both key and value should be string. If your keys are not string, they are automatically converted to strings.
But it is good practice to make sure both keys and values are strings before trying to save them.
Example