For testing purposes only - do not use for production.
I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted.
However, I am encountering an issue where on the second submission, the values are being overwritten instead of continuing the incrementation sequence (e.g., from value0 to value1 and so on).
The expected outcome should be:
- First submit: value0, value1, value2
- Second submit: value3, value4, value5
- Third submit: value6, value7, value8 and so on.
To achieve this functionality, I have the following JavaScript code:
document.getElementById('btn').addEventListener('click', createEntry());
function createEntry(){
const inputs = document.getElementsByTagName("input");
let i;
for (i = 0; i < inputs.length; i++) {
let value = inputs[i].value;
localStorage.setItem(`value${i}`, JSON.stringify(value));
}
};
In this script, all input elements are gathered by selecting all input tags, then looping through them to assign new statements to each value before storing it in localStorage. By incrementing the item name, we avoid overwriting any previously stored values.
The corresponding HTML structure would look like this:
<div class="form">
<input type="text" required>
<input type="text" required>
<input type="number" min="1" max="120" required>
<button type="button" id="btn">Add</button>
</div>