I'm Trying to make a list display in HTML of the stored details i put in my object using Javascript. which should look like this
name: Tester1 , age: 1
name: Tester2 , age: 2
name: Tester3 , age: 3
I used for in loop to display all the inputted objects, but it this happened
Actual:
name: Tester1 , age: 1name: Tester1 , age: 1name: Tester2 , age: 2name: Tester1 , age: 1name: Tester2 , age: 2name: Tester3 , age: 3
Here is the code for the Jascript
var person = [];
function profile(e) {
//to stop form from resubmitting
e.preventDefault();
var pProfile = {
name: document.getElementById('name').value,
age: document.getElementById('age').value
}
person.push(pProfile);
//used to convert result to string
var myJSON = JSON.stringify(person);
document.forms[0].reset();
//display in Final Obejct div
document.getElementById("fObject").innerHTML = myJSON;
//display converted objects to
for (let x in person){
document.getElementById("rFormat").append("name: " + person[x].name + " , " + "age : " + person[x].age + "<br>");
console.log(person[x]);
}
}
And this is for the HTML
<div id="part1">
<h3>Part 1</h2>
<form id="profile" onsubmit="profile(event)" action="#">
Name: <input type="text" id ="name">
Age: <input type="text" id ="age">
<input type="Submit" value="Add">
</form>
<h4>Final Object</h4>
<div id="fObject"></div>
<h4>Readable Format</h4>
<div id="rFormat"></div>
</div>
Pretty sure that I did something wrong with the for in loop, but i don't know exactly where. Please help. I'm new in javascript. Thanks so much.