0

I'm trying to let the user create an account, when the user has entered their details and clicks the button, an object is made based on the User class, and this should then be added to the 'users' array. When I run it, objects are created correctly however are not added to the array. Does anyone know why is this is? Thanks

const users = []

class User {
  constructor(f, s, u, e) {
    this.firstName = f
    this.surName = s
    this.userName = u
    this.email = e
  }
}

function formSubmit() {
  let fname = document.getElementById("firstname").value
  let sname = document.getElementById("surname").value
  let email = document.getElementById("email").value
  let uname = document.getElementById("username").value

  if ((fname.length == 0) || (sname.length == 0) || (email.length == 0)) {
    window.alert("Some boxes were unfilled")

  } else {
    if (checkEmail(email) == true) {
      //document.getElementById("output").innerHTML = "Account created successfully" 
      window.alert("Account created successfully")
    } else {
      window.alert("Email address invalid")
    }
  }

  users.push(new User(fname, sname, uname, email))


}
<form>
  <label for="fname"></label>
  <input type=t ext id="firstname" placeholder="First name" required>
  <p></p>

  <label for="sname"></label>
  <input type=t ext id="surname" placeholder="Surname" required>
  <p></p>

  <label for="uname"></label>
  <input type=t ext id="username" placeholder="Username" required>
  <p></p>

  <label for="email"></label>
  <input type=t ext id="email" placeholder="Email" required>
  <p id="eMessage"></p>

  <button onclick="formSubmit()" type="submit">Create account</button>


</form>
David
  • 208,112
  • 36
  • 198
  • 279
  • 3
    Use `onsubmit` event handler and prevent the submit action if you are trying to perform client-side operations. – Rayon Aug 18 '22 at 13:07
  • (1) The form is submitting and reloading the page. Since you're not really using the `
    ` element, just remove it. (2) `checkEmail` isn't defined anywhere. (3) Once those are corrected, the code works just fine.
    – David Aug 18 '22 at 13:08
  • 1
    @David or better, use the form and add an eventlistener that handles the submit event as suggested. `document.querySelector("form").addEventListener("submit",formSubmit); function formSubmit(e) { e.preventDefault(); /* rest of the code */ })` – mplungjan Aug 18 '22 at 13:09

0 Answers0