Isabel Gomez
Isabel Gomez

Reputation: 31

Show JSON by clicking a button

How can I show the JSON object that is in the random by clicking the button. With Javascript.

 var myObject = {
        "catalogo": [
            {
                "id" : "001",
                "name":"Nike",
                "desc" : "shoes",
                "price": 500,
            },
            {
                "id" : "002",
                "name":"MIKEY",
                "desc" : "shoes",
                "price": 500,
            },
            {
                "id" : "003",
                "name":"VANS",
                "desc" : "shoes",
                "price": 500,
            },
            {
                "id" : "004",
                "name":"SPORT",
                "desc" : "shoes",
                "price": 500,
            }
            ]
    };

var random = myObject.catalogo[Math.floor(Math.random()* myObject.catalogo.length)];
document.getElementById('table').innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";

HTML CODE: Here is the code for the button to display the value.

    <div>
         <div id="random"></div>
         <button>Añadir</button>
   </div>

I want to show it here

<div>
    <p class="line"></p>
</div>

Upvotes: 1

Views: 1592

Answers (2)

Pedro Castilho
Pedro Castilho

Reputation: 10532

Change your button to <button id="anadir">Añadir</button>.

After doing this, you can get your button from JS after the document loads:

window.addEventListener("DOMContentLoaded", function(event) {
  var myAddButtton = document.getElementById('anadir');
  myAddButton.onclick = function() {
    var random = myObject.catalogo[
      Math.floor(Math.random()* myObject.catalogo.length)
    ];

    document.querySelector('.line')
      .innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
  }
}

Load this in a <script> tag in your page and it should work.

Upvotes: 1

Kevin Jantzer
Kevin Jantzer

Reputation: 9451

This is how you would do it.

Take note, you also had some errors in your logic for getting the random data. The table ID doesn't exist (changed to line) and shortname isn't in your data (changed to name)

var myObject = {
  "catalogo": [{
      "id": "001",
      "name": "Nike",
      "desc": "shoes",
      "price": 500,
    },
    {
      "id": "002",
      "name": "MIKEY",
      "desc": "shoes",
      "price": 500,
    },
    {
      "id": "003",
      "name": "VANS",
      "desc": "shoes",
      "price": 500,
    },
    {
      "id": "004",
      "name": "SPORT",
      "desc": "shoes",
      "price": 500,
    }
  ]
};

function showRandom() {

  var random = myObject.catalogo[Math.floor(Math.random() * myObject.catalogo.length)];
  
  document.querySelector('.line').innerHTML = random.name + "<br>" + "$" + random.price + ".00";

}
<div>
  <div id="random"></div>
  <button onclick="showRandom()">Añadir</button>
</div>

<div>
  <p class="line"></p>
</div>

Upvotes: 2

Related Questions