Well i have a small project where i want to make an HTML form with Name and Surname that are saved into an array of objects. Sounds simple and cool. Well its until you start making it...
It just doesnt save the data and refreshes the page every time and .preventDefault doesnt help.
And for some reason addPerson function fires even if the submit is not clicked, have absolutely no idea how - event listener is set on click - why does it execute finction that is not called, but only defined?
<!DOCTYPE html>
<html>
<body>
<form>
<input id="firstName" type="text"> <br>
<input id="lastName" type="text"> <br>
<input id="age" type="number"> <br>
<button id="submit" type="submit">
Submit!
</button>
</form>
<script src="form.js"></script>
</body>
</html>
var submit = document.getElementById("submit");
function Person (FirstName, LastName, Age) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
var peopleArray = [];
function addPerson () {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var age = document.getElementById("age").value;
function createObject () {
var newObject = new Person (firstName, lastName, age);
peopleArray.push(newObject);
}
createObject ();
console.log("New person and added to list!" + " " + firstName + " " + lastName + " " + age);
console.log(peopleArray.length);
}
submit.addEventListener("click", addPerson());```
addPerson()here should be simplyaddPerson