I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items.
When I add a 3rd item to the array, it unexpectedly becomes the 2nd item in the displayed list. It seems that the items are appearing in a random order, which is confusing me.
Below is the code snippet I have been working on:
<body>
<h2>Local Storage - JavaScript</h2>
<form method="post" action="index.html" id="form">
<fieldset>
<legend>Insert Data</legend>
<input id="enterKey" type="text" placeholder="Enter Key...">
<input id="enterValue" type="text" placeholder="Enter Value...">
<input type="submit" value="Set Reminder">
</fieldset>
</form>
<ul id="output">
</ul>
</body>
<script>
form.addEventListener('submit', function(e) {
const key = enterKey.value;
const value = enterValue.value;
if (key && value) {
localStorage.setItem(key, value);
}
})
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
var li = document.createElement("li");
li.textContent = `${key}: ${value}</li>`;
output.appendChild(li);
}
</script>