Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
Having trouble getting values from an array of objects in javascript

I am making a program to get user input from HTML forms and compile them into an object for each user. So, I have an HTML form, I make a constructor, then I set up a click event to make the object, then I put it in the variable, and then I am trying to put that variable in an array of objects, before finally using a for loop to get all of the information from each object in this array. However, I am having trouble with that last part (or at least I think). Every time I run the code, the console log does display the message, but it is coming up with undefined rather than the user input. Can someone help please?

function user(firstName, lastName, address) {
  user.firstName = firstName;
  user.lastName = lastName;
  user.address = address;
}

var users = [];

document.addEventListener("submit", function(addUser) {

  event.preventDefault();

  var newUser = new user(
    document.getElementById("userFName").value,
    document.getElementById("userLName").value,
    document.getElementById("userAdd").value
  );

  users.push(newUser);

  for (let i = 0; i < users.length; i++) {
    console.log("User" + (i + 1) + "'s first name is " + users[i].firstName + ", their last name is " + users[i].lastName + ", and their address is " + users[i].address);
  }

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WWW</title>

  <style>

  </style>

</head>

<body>

  <form>
    <input id="userFName" placeholder="First Name">
    <input id="userLName" placeholder="Last Name">
    <input id="userAdd" placeholder="Address">
    <button type="submit">Submit</button>
  </form>

</body>

</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

By assigning to user, you're assigning to a property of the constructor, not a property of the instance. new User will mutate the constructor and return an empty object whose internal prototype is user.prototype.

Assign to this instead inside the constructor, to change the instance that gets returned.

function user(firstName, lastName, address) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.address = address;
}

var users = [];

document.addEventListener("submit", function(addUser) {

  event.preventDefault();

  var newUser = new user(
    document.getElementById("userFName").value,
    document.getElementById("userLName").value,
    document.getElementById("userAdd").value
  );

  users.push(newUser);

  for (let i = 0; i < users.length; i++) {
    console.log("User" + (i + 1) + "'s first name is " + users[i].firstName + ", their last name is " + users[i].lastName + ", and their address is " + users[i].address);
  }

});
<form>
  <input id="userFName" placeholder="First Name">
  <input id="userLName" placeholder="Last Name">
  <input id="userAdd" placeholder="Address">
  <button type="submit">Submit</button>
</form>

Or use a plain object instead of a constructor.

const user = (firstName, lastName, address) => ({
  firstName, lastName, address
});
const users = [];

document.addEventListener("submit", function(addUser) {

  event.preventDefault();

  var newUser = user(
    document.getElementById("userFName").value,
    document.getElementById("userLName").value,
    document.getElementById("userAdd").value
  );

  users.push(newUser);

  for (let i = 0; i < users.length; i++) {
    console.log("User" + (i + 1) + "'s first name is " + users[i].firstName + ", their last name is " + users[i].lastName + ", and their address is " + users[i].address);
  }

});
<form>
  <input id="userFName" placeholder="First Name">
  <input id="userLName" placeholder="Last Name">
  <input id="userAdd" placeholder="Address">
  <button type="submit">Submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Relatório

0

make your life easier, use names in your forms!

const
  myForm = document.querySelector('#my-form')
, users  = []
  ;
myForm.onsubmit = e =>
  {
  e.preventDefault()

  users.push({ firstName: myForm.userFName.value
             , lastName : myForm.userLName.value
             , address  : myForm.userAdd.value
            })

  console.clear()
  users.forEach( (user,i) => console.log(i,JSON.stringify(user)) )

  myForm.reset()  // clear inputs 
  myForm.userFName.focus()
  }
<form id="my-form">
  <input name="userFName" placeholder="First Name" required >
  <input name="userLName" placeholder="Last Name"  required >
  <input name="userAdd"   placeholder="Address"    required >
  <button type="submit">Submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda