Display an object array in Divs

Asked

Viewed 203 times

-1

I am facing problems taking input values, storing in variables, and then passing these variables to an array of objects. I would also like to later display these values within each separate div and at the end add all div in one div only.

What should I do? Can you help me?

var dia = document.querySelector('#datas').value; //input
var conteudo = document.querySelector('#descricao').value; //input
var valores = document.querySelector('#valor').value; //input
var btn = document.querySelector('#btn');
var osGastos = document.querySelector('#osGastos'); //div

var gastos = {
        data:"",
        descricao:"",
        valor:"",
        set dat(value) {
            this.data = value;
        },
        set descri(value) {
            this.descricao = value;
        },
        set vall(value) {
            this.valor = value;
        }
    };

function exibeGastos() {
    for (var i = 0; i < gastos.data.length && gastos.descricao.length && gastos.valor.length; i++) {
        var divElement = document.createElement('div');
        var divElement1 = document.createElement('div');
        var divElement2 = document.createElement('div');
        var divText = document.createTextNode(gastos.data[i]);
        var divText1 = document.createTextNode(gastos.descricao[i]);
        var divText2 = document.createTextNode(gastos.valor[i]);

        
        divElement.appendChild(divText);
        divElement1.appendChild(divText1);
        divElement2.appendChild(divText2);

        osGastos.appendChild(divElement);
        osGastos.appendChild(divElement1);
        osGastos.appendChild(divElement2);
    }
}
exibeGastos();

function addGasto() {
    var dia = document.querySelector('#datas').value;
    var conteudo = document.querySelector('#descricao').value;
    var valores = document.querySelector('#valor').value;

    gastos.dat = dia; 
    gastos.descri = conteudo;
    gastos.vall = valores;

    dia.value = '';
    conteudo.value = '';
    valores.value = '';
    exibeGastos();
}

btn.onclick = addGasto;

function moeda(a, e, r, t) {
    let n = ""
      , h = j = 0
      , u = tamanho2 = 0
      , l = ajd2 = ""
      , o = window.Event ? t.which : t.keyCode;
    if (13 == o || 8 == o)
        return !0;
    if (n = String.fromCharCode(o),
    -1 == "0123456789".indexOf(n))
        return !1;
    for (u = a.value.length,
    h = 0; h < u && ("0" == a.value.charAt(h) || a.value.charAt(h) == r); h++)
        ;
    for (l = ""; h < u; h++)
        -1 != "0123456789".indexOf(a.value.charAt(h)) && (l += a.value.charAt(h));
    if (l += n,
    0 == (u = l.length) && (a.value = ""),
    1 == u && (a.value = "0" + r + "0" + l),
    2 == u && (a.value = "0" + r + l),
    u > 2) {
        for (ajd2 = "",
        j = 0,
        h = u - 3; h >= 0; h--)
            3 == j && (ajd2 += e,
            j = 0),
            ajd2 += l.charAt(h),
            j++;
        for (a.value = "",
        tamanho2 = ajd2.length,
        h = tamanho2 - 1; h >= 0; h--)
            a.value += ajd2.charAt(h);
        a.value += r + l.substr(u - 2, u)
    }
    return !1
}
<main>
     <p style="position:fixed; background-color: white; width: 100%; margin-top: -20px; font-size: 1.2em;">Despesas</p>
     <section id="osGastos">
          
     </section>
   </main>
   <footer> 
     <input type="number" id="datas" placeholder="DIA" min="1" max="31">
     <input type="text" id="descricao" placeholder="DESCRIÇÃO">
     <input type="text" id="valor" placeholder="VALOR" onKeyPress="return(moeda(this,'.',',',event))">
     <button id="btn">OK</button>
    </footer>
    <script src="js/main.js"></script>

  • managed to solve your problem?

1 answer

1

I wouldn’t use Divs to do this construction, but since your question was specific, see the example below.

let registros = [];
let btn = document.querySelector('#btn');
let osGastos = document.querySelector('#osGastos'); //div

function addGasto() {
  //recuperando as informações inputadas
  let dia = document.querySelector('#datas').value;
  let descricao = document.querySelector('#descricao').value;
  let valor = document.querySelector('#valor').value;
  
  //montando o objeto com o registro
  let registro = {
    dia,
    descricao,
    valor
  };
  
  //adiciona o objeto para o array
  registros.push(registro);
  
  //executa a rotina de exibição
  exibeGastos();
}

function exibeGastos() {
  //ordenando o array pelo dia
  registros = registros.sort((a, b) => (a.dia > b.dia) ? 1 : ((b.dia > a.dia) ? -1 : 0));

  //limpando o conteúdo da section
  osGastos.innerHTML = "";

  //loop para repopular a exibição dos registros
  for (var i = 0; i < registros.length; i++) {
    //criando as divs das colunas
    let divDia = document.createElement('div');
    let divDescricao = document.createElement('div');
    let divValor = document.createElement('div');

    //atribuindo o conteúdo
    divDia.innerText = registros[i].dia;
    divDescricao.innerText = registros[i].descricao;
    divValor.innerText = registros[i].valor;

    //ajustando a apresentacao
    divDia.className = "colunaDia";
    divDescricao.className = "colunaDescricao";
    divValor.className = "colunaValor";

    //criando div pai para agrupar os registros da linha
    let divRow = document.createElement('div');
    divRow.className = "linha";

    //adicionando os divs "coluna"
    divRow.appendChild(divDia);
    divRow.appendChild(divDescricao);
    divRow.appendChild(divValor);

    //adicionando o elemento criado
    osGastos.appendChild(divRow);
  }

}

btn.onclick = addGasto;

function moeda(a, e, r, t) {
  let n = "",
    h = j = 0,
    u = tamanho2 = 0,
    l = ajd2 = "",
    o = window.Event ? t.which : t.keyCode;
  if (13 == o || 8 == o)
    return !0;
  if (n = String.fromCharCode(o), -1 == "0123456789".indexOf(n))
    return !1;
  for (u = a.value.length,
    h = 0; h < u && ("0" == a.value.charAt(h) || a.value.charAt(h) == r); h++)
  ;
  for (l = ""; h < u; h++)
    -
    1 != "0123456789".indexOf(a.value.charAt(h)) && (l += a.value.charAt(h));
  if (l += n,
    0 == (u = l.length) && (a.value = ""),
    1 == u && (a.value = "0" + r + "0" + l),
    2 == u && (a.value = "0" + r + l),
    u > 2) {
    for (ajd2 = "",
      j = 0,
      h = u - 3; h >= 0; h--)
      3 == j && (ajd2 += e,
        j = 0),
      ajd2 += l.charAt(h),
      j++;
    for (a.value = "",
      tamanho2 = ajd2.length,
      h = tamanho2 - 1; h >= 0; h--)
      a.value += ajd2.charAt(h);
    a.value += r + l.substr(u - 2, u)
  }
  return !1
}
div {
  display: inline-block;
  float: left;
  position: relative;
}

.linha {
  width: 100%;
}

.colunaDia {
  width: 65px;
}

.colunaDescricao {
  width: 170px;
}

.colunaValor {
  width: 170px;
}
<html>

<body>
  <main>
    <h2>Despesas</h2>
    <section id="osGastos"></section>
  </main>
  <footer>
    <form action="">
      <input type="number" id="datas" placeholder="DIA" min="1" max="31">
      <input type="text" id="descricao" placeholder="DESCRIÇÃO">
      <input type="text" id="valor" placeholder="VALOR" onKeyPress="return(moeda(this,'.',',',event))">
      <button id="btn" type="reset">OK</button>
    </form>
  </footer>
</body>

</html>

I would like to make a few comments on the code by presenting and pointing out some errors...

The main thing about it is the confusion you made about creating an object to store the values, but try to navigate it as if you were working with three different vectors for each property.

for (var i = 0; i < gastos.data.length && gastos.descricao.length && gastos.valor.length; i++) {
        var divText = document.createTextNode(gastos.data[i]);
        var divText1 = document.createTextNode(gastos.descricao[i]);
        var divText2 = document.createTextNode(gastos.valor[i]);

JavaScript is a dynamic language, it doesn’t make much sense for you to declare the structure of the object and define your setters in the case where there is no complexity at all.

See that:

var gastos = {
        data:"",
        descricao:"",
        valor:"",
        set dat(value) {
            this.data = value;
        },
        set descri(value) {
            this.descricao = value;
        },
        set vall(value) {
            this.valor = value;
        }
    };

Turned out to be just that:

  let registro = {
    dia,
    descricao,
    valor
  };

When the variable and attribute have the same name, the declaration is sufficient for the name and value to be set. This is already one of the advantages of not declaring two variables as Element,Element1, Div1, Div2 and etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.