I”m still new to JS and localStorage and I’m trying to understand it better. I am trying to be able to take 2 inputs from the user and when a button is clicked it displays those values (sort of like a todo list). I’m trying to implement localStorage and I’m able to save the key/value pair but I can’t seem to display them properly. I’m able to click the button and display the values the first time I do it but the second click gives me a “Unexpected non-whitespace character after JSON at position 24 (line 1 column 25)” console message after.
Can someone help me understand what the problem is?
My goal is figure out how to display multiple items stored in a object.
Here is my code
HTML
<body>
<div class="container">
<input type="text" class="inputField">
<input type="text" class="inputFieldTwo">
<button id="btn">Click</button>
<div class="sample">
</div>
</div>
<script src="main.js"></script>
</body>
JS
const userInput = document.querySelector(".inputField");
const userInputTwo = document.querySelector(".inputFieldTwo");
const button = document.querySelector("#btn");
const contain = document.querySelector('.sample');
let arr = [];
button.addEventListener("click", () => {
let thisObj = {
user: `${userInput.value}`,
num: `${userInputTwo.value}`
}
let strObj = JSON.stringify(thisObj);
arr.push(strObj)
localStorage.setItem("data", arr)
let parseObj = JSON.parse(arr);
for (let i = 0; i < arr.length; i++) {
let input = document.createElement("input");
let inputTwo = document.createElement("input");
input.type = "text";
inputTwo.type = "number";
input.value = parseObj.user
inputTwo.value = parseObj.num
localStorage.setItem("data", JSON.stringify(arr));
contain.appendChild(input);
contain.appendChild(inputTwo);
return
}
})