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
Passing in variables from JS object into an html button

Goal:

I am trying to populate variables of a function inside of an 'onclick' attribute of a dynamically created button using javascript and HTML. When I press the button, I want to execute a function based off of the variables inside the button. The variables come from a JS object (or rather, a specific object within a list of objects).

This is what I've tried:

var testDivElement = document.getElementById("testDiv");

//Object
var locations = [{
    name: "Califonia",
    address: "Califonia Test Address",
    times: [1, 2, 3, 4, 5]
  },
  {
    name: "Idaho",
    address: "Idaho Test Address",
    times: [1, 2, 3]
  },
  {
    name: "Iowa",
    address: "Iowa Test Address",
    times: [0]
  }
];

//Function
function createDivs() {
  var content;
  for (i in locations) {
    content += '<div>' +
      '<p>' + locations[i].name + '</p>' +
      '<p>' + locations[i].address + '</p>' +
      '<button onclick="readDataToConsole(' + location[i].name + ',' + location[i].address + ',' + location[i].times + ')">Press Me</button>';

  }
  testDivElement.innerHTML = content;
}

function readDataToConsole(name, address, times) {
  console.log(name);
  console.log(address);
  for (i in times) {
    console.log(times[i]);
  }
}
<body>
  <button onclick="createDivs()">clickMeNow</button>
  <div id="testDiv"></div>
</body>

I am able to generate what is in the <p> tags when I do not try to include the <button> tag.

I can't find anything else online that could help me with this.

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

0

Put quotes around the string arguments to readDataToConsole(). Use JSON.stringify() to convert the times array to an array literal.

And to make the code easier to read and write, use a template literal instead of lots of string concatenation.

var testDivElement = document.getElementById("testDiv");

//Object
var locations = [{
    name: "California",
    address: "California Test Address",
    times: [1, 2, 3, 4, 5]
  },
  {
    name: "Idaho",
    address: "Idaho Test Address",
    times: [1, 2, 3]
  },
  {
    name: "Iowa",
    address: "Iowa Test Address",
    times: [0]
  }
];

//Function
function createDivs() {
  var content = '';
  for (let i in locations) {
    content += `<div><p>${locations[i].name}</p>
      <p>${locations[i].address}</p>
      <button onclick="readDataToConsole('${locations[i].name}', '${locations[i].address}', ${JSON.stringify(locations[i].times)})">Press Me</button>`;
  }
  testDivElement.innerHTML = content;
}

function readDataToConsole(name, address, times) {
  console.log(name);
  console.log(address);
  for (i in times) {
    console.log(times[i]);
  }
}
<body>
  <button onclick="createDivs()">clickMeNow</button>
  <div id="testDiv"></div>
</body>

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