0

I create a function in which my input values of form are being collected in an object then afterwards I push whole object in an array and save my array in local Storage...But the problem is when I change the value and sign up again my old values are overwritten with new one but I want it to push on index 1 of array so that my array contain 2 objects and so on... Please help me Thanking You.

    <script>
        var labelsarray = document.getElementsByTagName("label");
        var inputsarray = document.getElementsByTagName("input");
        var array = [];
        function subm() {
            var users = {
                FirstName: inputsarray[0].value,
                LastName: inputsarray[1].value,
                UserName: inputsarray[2].value,
                Password:  inputsarray[3].value,
                DateofBirth: inputsarray[4].value,
                Age: inputsarray[5].value,
                Purpose: ""
            };
            if (inputsarray[6].checked === true) {
                users.Gender = "Male";
            }
            else if (inputsarray[7].checked === true) {
                users.Gender = "Female";
            }
            if (inputsarray[8].checked === true) {
                users.Purpose += " Storing Apps";
            }
            if (inputsarray[9].checked === true) {
                users.Purpose += " Storing Sites";
            }
            if (inputsarray[10].checked === true) {
                users.Purpose += " Fun";
            }
            array.push(users);
            for (var i=0;i<array.length;i++) {
                localStorage.setItem("User Data: ", JSON.stringify(array[i]));
            }
        }
    </script>
    <div>
        <center>
            <form action="Javascript:void(0);"method="post" onsubmit="subm();">
                <label for="fname">First Name:</label>&emsp;
                <input type="text" id="fname" />
                <br/>
                <label for="lname">Last Name:</label>&emsp;
                <input type="text" id="lname" />
                <br/>
                <label for="uname">User Name:</label>&emsp;
                <input type="text" id="uname" />
                <br/>
                <label for="pass">Password:</label>&emsp;&ensp;&nbsp;
                <input type="text" id="pass" />
                <br/>
                <label for="dob">Date of Birth:</label>&emsp;&emsp;&nbsp;
                <input type="date" id="dob" />
                <br/>
                <label>Age:</label>&emsp;&emsp;&emsp;&emsp;&emsp;
                <input type="text" id="age" />
                <br/>
                <span>Gender:</span>&emsp;&emsp;&emsp;&emsp;&ensp;
                <input type="radio" name="gender" id="male" />
                <label for="male">Male</label>
                <input type="radio" name="gender" id="female" />
                <label for="female">Female</label>
                <br/>
                <p>For what purpose(s) you are making account?</p>
                <input type="checkbox" id="app" name="purpose" value="storingapps" />
                <label for="app">Storing Apps</label>
                <input type="checkbox" id="site" name="purpose" value="storingsites" />
                <label for="site">Storing Sites</label>
                <input type="checkbox" id="fun" name="purpose" value="fun" />
                <label for="fun">Fun</label>
                <br/>
                <input type="submit" value="Submit"  class="button" />
            </form>
        </center>
    </div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Arham Awan
  • 584
  • 5
  • 9

4 Answers4

0

Each time you save in your local storage you are saving just the last item. Because each save will be replaced by the next one and only the last one would be visible. Instead you only need to save the array into the local storage

// (not needed) for (var i=0;i<array.length;i++) {
    localStorage.setItem("User Data: ", JSON.stringify(array));
// (not needed) }

Now your local storage will have array of objects

Prasanna
  • 4,125
  • 18
  • 41
0

You're recreating your array every time instead of reading it from Local Storage. As such, you're starting with a fresh array every time.

Where you're doing var array = []; you should be reading from local storage.

For example:

var array = [];
var savedArrayJSON = localStorage.getItem("userData");

if (savedArray) {
   try {
     array = JSON.parse(savedArrayJSON);
   } catch (e) {
     // Probably do nothing
   }
}

...

array.push(users);

// No more for-loop
localStorage.setItem("userData", JSON.stringify(array));
SamA
  • 587
  • 3
  • 6
0

After you set up your array, you loop through it and upon each iteration you are overwriting the User Data key from the last iteration in localStorage, so only the last array item is getting stored:

for (var i=0;i<array.length;i++) {
  localStorage.setItem("User Data: ", JSON.stringify(array[i]));
}

You should just set the entire array into local storage or make distinct keys to store the individual items with:

localStorage.setItem("User Data: ", JSON.stringify(array));

Next, each time someone comes to your page, you create a new, empty array, so when does the data in localStorage ever get pulled out and used? Upon page access, you should be getting the saved data so that you can push more into it:

// Set the array variable equal to the array in localStorage or an empty array
var array = JSON.parse(localStorage.getItem("User Data")) || [];

ADDITIONAL NOTES:

Your HTML is not valid and follows out of date methodologies.

Javascript:void(0);

Is not only mis-capitalized (should be: javascript:void()), but that entire technique for doing nothing shouldn't be used as well as onsubmit (HTML event handling attributes). All your JavaScript should be in dedicated scripts and event handling should be done using element.addEventListener().

<center> is deprecated. All formatting should be done with CSS.

<input> and <br> elements should not use the XML self-terminating syntax of /> at the end of the tag. While this is legal, it is a left-over relic of 2000 when the world thought that XML was going to be the future. It buys you nothing in your code and can lead to bugs when not used correctly.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You can try the following code.This occurs because you are overwriting the localStorage values everytime you are creating a new user.A simple solution is to store the users in array format and appending new users to it everytime a new user fill up form and then save it to the localStorage.

```

<script>


 var labelsarray = document.getElementsByTagName("label");
  var inputsarray = document.getElementsByTagName("input");

  //Here We first Grab the already stored value from the localStorage and parse it because it is in string format.

  var array = JSON.parse(localStorage.getItem('User Data: ')) || [];

  function subm() {
      var users = {
          FirstName: inputsarray[0].value,
          LastName: inputsarray[1].value,
          UserName: inputsarray[2].value,
          Password:  inputsarray[3].value,
          DateofBirth: inputsarray[4].value,
          Age: inputsarray[5].value,
          Purpose: ""
      };
      if (inputsarray[6].checked === true) {
          users.Gender = "Male";
      }
      else if (inputsarray[7].checked === true) {
          users.Gender = "Female";
      }
      if (inputsarray[8].checked === true) {
          users.Purpose += " Storing Apps";
      }
      if (inputsarray[9].checked === true) {
          users.Purpose += " Storing Sites";
      }
      if (inputsarray[10].checked === true) {
          users.Purpose += " Fun";
      }

  //We Now append the users to the array and save it to localStorage.
      array.push(users);
      localStorage.setItem("User Data: ", JSON.stringify(array));          
  }

``` I hope this works for you also.