简体   繁体   中英

Creating a button with each input JSON object using JavaScript

I got a situation where I would like to read some data off a JSON format, however I am having some issues understanding how I should construct the button dynamically from JSON object.
My scenario is as follows:

$(document).ready(function() {
  var socket = io.connect('http://' + document.domain + ':' + location.port);
  // listen for mqtt_message events
  // when a new message is received, log and append the data to the page
  socket.on('mqtt_message', function(data) {
    var json = JSON.parse(data['payload']);
    var table = $("<table>");
    table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
    for (var i = 0; i < json.length; i++) {
      var row = $("<tr><td>" + json[i]["name"] +  json[i]["ID"] + "</td></tr>");  
      table.append(row);
    }  
    table.appendTo($("#container"));
  })
});

where

json = {"host":abc,"name":123,"id":345}

I have to make hostname as button and when I click on that button for example here, name "abc", i will get details name and id in table format. I have created table but it is showing whole table not that scenario which I actually want.

I am new to the JavaScript, facing issues here.

let json = [
    {"host":abc,"name":123,"id":345},
    {"host":def,"name":456,"id":345}
]

In your html write

<button *ngFor = 'let item of json' (click)='buttonOnClick($event)'>
    {{item.host}}
</button>

Above code will render two buttons for each element in the array

In your ts write

buttonOnClick(event) {
    console.log(event) // you will get the corresponding object from the array
}

1) The JSON data doesn't seem to be an array, you can't loop through it.

2) You have to append the header to a <thead> element.

3) You have to append the table row to a <tbody> element.

All tables should have a <thead> and a <tbody> element , so just add it to your HTML code.

 <div id="container">

   <table style="display:none">
     <thead>
       <tr>
         <th>Host</th>
         <th>Name</th>
         <th>ID</th>
       </tr>
     </thead>

     <tbody></tbody>
   </table>

 </div>

Then you append your data to these HTML elements, like so. If your data is an object and not an array, just don't loop through it but instead call the properties as is.

  var json = [{
     host: "Some host IP",
     name: "Some name",
     id: 345
   },
   {
     host: "Some other host IP",
     name: "Some other name",
     id: 987
   }
 ];

 var $container = $("#container");
 var $thead = $("#container table thead");
 var $tbody = $("#container table tbody");
 var $row = $("#container table tbody tr");

 // Loop through items in JSON data..
 json.forEach(function(item) {
   var $button = $("<button>" + item.host + "</button>");
   $container.prepend($button);

     // Button click handler..
   $button.on("click", function() {

     // Replace row HTML..
     $row.html('<td>' + item.host + '</td>' + '<td>' + item.name + '</td>' + '<td>' + item.id + '</td>');

     // Show table if it's not already visible..
     $("#container table").show();

   });
 });



Full code here:
https://jsfiddle.net/amsv/15h74uy6/


Vanilla JS, ie. without jQuery:
https://jsfiddle.net/amsv/15h74uy6/72/

var sampleData = [{ "host": "abc", "name": 123, "id": 345 }, { "host": "xyz", "name": 456, "id": 678 }]

When data is received you should create button which shows table and set data attribute of button with received data.

for (var i = 0; i < sampleData.length; i++) {
            var item = sampleData[i];
            var button = $('<button />');
            button.text(item.host);
            button.data('data', JSON.stringify(item))
            button.on('click', function (e) {
                e.preventDefault();
                showTable(e);
            });
            $('#buttons').append(button);
        }

showTable is like as below

    function showTable(e) {
        var json = JSON.parse($(e.target).data('data'));
        var table = $("<table>");
        table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
        var row = $("<tr><td>" + json["host"] + "</td><td>" + json["name"] + "</td><td>" + json["id"] + "</td></tr>");
        table.append(row);
        $("#table").html(table);
    }

Html is below:

    <div id="container">
        <div id="buttons">
        </div>
        <div id="table">
        </div>
    </div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM