I am trying to write a simple banking app to learn basic DOM manipulation stuff. This will be a single page website with lots of function calls and hiding/displaying containers.
Once I click the register button on the main screen, it calls registerScreen()
function which then hides the main screen elements and shows a form group with text boxes and a submit button that saves the filled in information. However, saveCustomer()
function calls itself as soon as I bring up the register screen. Obviously, it submits a blank form which is a problem.
I have tried different event listener methods like submit
, click
, getElementById().onclick
, and so on. I did not want to call saveCustomer()
function on HTML because I do not know how I can pass the info with that approach.
function registerScreen() {
document.getElementById("welcome-container").style.display = "none";
document.getElementById("registerScreen").style.display = "block";
let customerFirstName = document.getElementById('firstName').value;
let customerLastName = document.getElementById('lastName').value;
let customerPassword = document.getElementById('password').value;
let randomID = document.getElementById("randomID");
let ID = Math.floor((Math.random() * 999) + 100);
randomID.innerHTML += ID;
//This is the line I am having problems with
document.getElementById("submitInfo").addEventListener("click", saveCustomer(ID, customerFirstName, customerLastName, customerPassword));
}
function saveCustomer (ID, customerFirstName, customerLastName, customerPassword) {
let customer = {
id: ID,
firstname: customerFirstName,
lastname: customerLastName,
password: customerPassword,
cashAmount: 0,
}
if (localStorage.getItem("customers") === null) {
let customers = [];
customers.push(customer);
localStorage.setItem("customers", JSON.stringify(customers));
} else {
let customers = JSON.parse(localStorage.getItem("customers"));
customers.push(customer);
localStorage.setItem("customers", JSON.stringify(customers));
}
alert("Registration successful.");
}