0

I was trying to create an array in JSON format so that it stores name mailId and password of the user dynamically each time a new user signs up.I was able to create for one user but i am stuck in creating a loop and also to push the element in the array var user [];.can anyone suggest me how to do this ?

var user = [];
document.getElementById("sub").addEventListener("click",function store(){
	var user = {};
	user.name = document.getElementById("nme").value;
	user.emailId = document.getElementById("mail").value;
	user.password = document.getElementById("pd").value;
	console.log("user", user);
  });

2
  • update var user = {} to var _tmp = {} and at the end user.push(_tmp) Commented Sep 14, 2016 at 10:21
  • thanks a lot it worked!learned a new trick today Commented Sep 14, 2016 at 10:25

2 Answers 2

2

Switch the array name and then just push the user into it.

var users = [];
document.getElementById("sub").addEventListener("click",function store(){
    var user = {};
    user.name = document.getElementById("nme").value;
    user.emailId = document.getElementById("mail").value;
    user.password = document.getElementById("pd").value;
    console.log("user", user);
    users.push(user);
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Ideally for such small issues, you should comment.
0

If I understand correctly this should do the trick.

var userArray = [];
document.getElementById("sub").addEventListener("click",function store(){
    var user = {};
    user.name = document.getElementById("nme").value;
    user.emailId = document.getElementById("mail").value;
    user.password = document.getElementById("pd").value;
    userArray.push(user);
    console.log("user", user);
    console.log("userArray: ", userArray);
  });

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.