0

This is for testing purposes only.

i'm trying to store data from 3 inputs (types: text,number) and store them in localStorage. which continuously increment every submit.

i seem to be overwriting value0, value1, value2 on the second submission instead of further incrementing to value3, value4, value5.

expected result:

  1. first submit value0,value1,value2
  2. second submit value3,value4,value5
  3. third submit value6,value7,value8 etc.

JS:

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));

    }  
};

gather all input by grabbing all input tags, loop through found elements. assign new statement to looped values and store them in localStorage. increment the item name to avoid overwriting the previously looped item.

HTML:

<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>
2
  • hi @Plague3D can you provide proper explanation and add HTML code as well Commented Jan 8, 2020 at 8:34
  • @GaganV done to the best of my ability, I'm unsure how i can clarify my question further. Commented Jan 8, 2020 at 9:11

1 Answer 1

0

The way you coded it will override the saved values because i always gets reset to 0 when the function runs. There are many different ways to re-write your code, one being the below:

Store the last index used

// By the way, there was an error in this line, you were calling createEntry()
// instead of passing the function as a callback.
document.getElementById('btn').addEventListener('click', createEntry);

function createEntry() {
    const inputs = document.getElementsByTagName("input");

    let i;
    let index = getNextIndex();

    for (i = 0; i < inputs.length; i++) {
        let value = inputs[i].value; 
        localStorage.setItem(`value${index}`, JSON.stringify(value));
        index++;
    }

    localStorage.setItem('nextIndex', index);
}

function getNextIndex() {
    const index = localStorage.getItem('nextIndex');
    return index ? parseInt(index) : 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.