0

I'm a beginner in Js and have a problem making a little program, I want to put the variables nome, document e Codigo, inside of the JSON array 'registros'

var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: 0,
        nome: "",
        sexo: ""
    }];
    registro.push(codigo, nome, document);
}  
1
  • You named your array registros but then tried to push into registro which is not an array but an object Commented Feb 10, 2021 at 18:12

2 Answers 2

1

You need to do a little adjustment in the salvar() function. First, you can set each specific value of your "registro" var like this:

var registro = [{
    codigo: codigo, //value = 1
    nome: nome, //value = the innerText of document.getElementById("pNome")
    sexo: ""
}];

Then, you use the push() function to insert "registro" into your "registros" array. Here is the full updated code:

var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: codigo,
        nome: nome,
        sexo: ""
    }];
    registros.push(registro);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Array in JS comes in property/ value structure, and from your code you are assigning the values to a different variable registro instead of registros.

Moreover, the registros variable is never user. To do this;

  1. Create your array variable (registros)
  2. Create a function (salvar)
  3. Create an object that will hold your values, here nome in object will create a property name "nome" with the value being the value in nome which is document.get ...;
    var obj = { "nome": document.getElementById("pNome").innerText.
  4. Then push obj to array, registros
var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var obj = { nome, documento, caodigo}

    registros.push(obj);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.