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

105
Visualizações
how to add user data javascript

I am having trouble being able to add user input data. I can get it working when I add in the data myself all the users show up in the console in the array. For people 1-3 I would like them to enter their name and favorite color but I can't seem to be able to store it or at least have it come up in the console. I did remove person 2 and 3 from the array so I can test it easier and quicker. if you were to take the

    user: document.getElementById('name').value,
    color: document.getElementById('color').value,

and all the comments it would work and show up in console how i want it to but cant seem to do user data. Sorry if this is confusing i am a new to javascript.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <form>
        <div class="formBox">
            <label for="name">Name</label>
            <input type="text" id="name" placeholder="Name"/>
        </div>


        <div class="formBox">
            <label for="color">Favorite color</label>
            <input type="text" id="color" placeholder="Color"/>
        </div>

        <div class="formBox">
            <button id="btn">Click to Add</button>
        </div>
        <div id="msg">
            <pre></pre>
        </div>
    </form>
    

    <script >


const person1 = {
    user: document.getElementById('name').value,
    color: document.getElementById('color').value,

   /* user: "Sarah",
    color: "Yellow",*/
  };


  /* const person2 = {
    user: "Aaron",
    color: "Yellow"
  };
  
  const person3 = {
    user: "Sarah",
    color: "Green",
  };
  */
  array = [person1]
  
  sort = array.sort(function(a, b){
      if(a.user < b.user) { return -1; }
      if(a.user > b.user) { return 1; }
      return 0;
  })
  
  console.log(sort)



    </script>
</body>
</html>

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

0

I give you a code matches with your purpose but I recommend you found a course that builds a complete project, that can helps you to understands how to use basics to build some complex things.

// Declare Part
const users = [];
const form = document.getElementById("myForm");

// 1. Add Event Listener to our form
//   when form submits the function get called
form.addEventListener("submit", (event) => {
  // Stop form from refreshing the page
  event.preventDefault();

  // Get name field value
  const userName = document.getElementById("name").value;

  // Get color field value
  const userColor = document.getElementById("color").value;

  // Create new person
  const person = {
    user: userName,
    color: userColor,
  };

  // Store new person (Add new person to array of users)
  users.push(person);

  // Now we sort our users
  users.sort(function(a, b) {
    if (a.user < b.user) {
      return -1;
    }
    if (a.user > b.user) {
      return 1;
    }
    return 0;
  });

  // See the result
  console.log(users);
});
<form id="myForm">

  <div class="formBox">
    <label for="name">Name</label>
    <input type="text" id="name" placeholder="Name" />
  </div>

  <div class="formBox">
    <label for="color">Favorite color</label>
    <input type="text" id="color" placeholder="Color" />
  </div>

  <div class="formBox">
    <button id="btn">Click to Add</button>
  </div>

  <div id="msg">
    <pre></pre>
  </div>

</form>

about 4 years ago · Juan Pablo Isaza Relatório

0

The javascript in your code is running start to finish every time you refresh the page and when you're clicking the click to add button, you're submitting the form, which automatically refreshes the page. You can make a couple of tweaks in your code to fix this...

  1. You can add type="button" as a property of your button to tell the browser that this is a button and not a way of submitting your form. By doing this your page wont refresh when you click it.

  2. You want your javascript code to run when you click the button, not when the page loads. To do this you need to wrap it in a function and add an onclick handler to your button that executes the function when the button is clicked. You'll notice the array is initialised outside the function, this is because we do want the array to be initialised when you load the page, and not when the button is clicked, otherwise we would be overwriting the array every time we added something to it.

const array = []

const addUser = () => {
  const person1 = {
    user: document.getElementById('name').value,
    color: document.getElementById('color').value,
  };

  array.push(person1)

  sort = array.sort(function(a, b){
      if(a.user < b.user) { return -1; }
      if(a.user > b.user) { return 1; }
      return 0;
  })

  console.log(sort)

}
<form>
  <div class="formBox">
      <label for="name">Name</label>
      <input type="text" id="name" placeholder="Name"/>
  </div>


  <div class="formBox">
      <label for="color">Favorite color</label>
      <input type="text" id="color" placeholder="Color"/>
  </div>

  <div class="formBox">
      <button
        id="btn"
        type="button"
        onclick="addUser(this)"
      >Click to Add</button>
  </div>
  <div id="msg">
      <pre></pre>
  </div>
</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