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);
}
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);
}
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;
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.