how to add button in javascript since the data that import in the html table is from JSON file

Viewed 154

I am trying to add edit and delete button inside the column but the HTML table was created from JSON file and it is using for loop to print out the content. I don't know how to add extra button inside the column (green zone).

The button that plan to add will be replace in the 'undefined' col.

JSON code:


 [
   {
      "userId":"ravjy", 
      "jobTitleName":"Developer", 
      "firstName":"Ran",
      "lastName":"Vijay",
      "preferredFullName":"Ran Vijay",
      "employeeCode":"H9",
      "region":"DL",
      "phoneNumber":"34567689",
      "emailAddress":"ranvijay.k.ran@gmail.com"
   },
   {
      "userId":"mrvjy",
      "jobTitleName":"Developer",
      "firstName":"Murli",
      "lastName":"Vijay",
      "preferredFullName":"Murli Vijay",
      "employeeCode":"A2","region":"MU",
      "phoneNumber":"6543565",
      "emailAddress":"murli@vijay.com"
      }
   ]
<script>
fetch('employees.json')
  .then(function (response) {
    // The JSON data will arrive here
     return response.json();
  })
    .then(function (data) {
    appendData(data);
  })
  .catch(function (err) {
    // If an error occured, you will catch it here
  });
        
    function appendData(data) {
        
        //Extract Value for HTML HEADER.
        
        var col=[];
        for (var i = 0; i<data.length;i++){
            for (var key in data[i]){
                if (col.indexOf(key) === -1){
                    col.push(key);
                }
            }
        }
        
        //Add edit and delete header
        col.push("Edit","Delete");
        
        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
        
        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }
        
           // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < data.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = data[i][col[j]];
                
            }
        }
        
        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("myData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
    
   
    
    </script>


  [1]: https://i.stack.imgur.com/YpoDi.png
  [2]: https://i.stack.imgur.com/pu7SB.png
1 Answers

Solution

Javascript map will help to get that working

const data = [
  {
    userId: "ravjy",
    jobTitleName: "Developer",
    firstName: "Ran",
    lastName: "Vijay",
    preferredFullName: "Ran Vijay",
    employeeCode: "H9",
    region: "DL",
    phoneNumber: "34567689",
    emailAddress: "ranvijay.k.ran@gmail.com",
  },
  {
    userId: "mrvjy",
    jobTitleName: "Developer",
    firstName: "Murli",
    lastName: "Vijay",
    preferredFullName: "Murli Vijay",
    employeeCode: "A2",
    region: "MU",
    phoneNumber: "6543565",
    emailAddress: "murli@vijay.com",
  },
];

function test(type, id) {
  alert(type + " " + id);
}

function appendData(data) {
  //Extract Value for HTML HEADER.
  data = data.map((item) => {
    item.Edit_Delete = `<Button type="button" onclick="test('Edit', '${item.userId}')">${item.userId}</Button>
<Button type="button" onclick="test('Delete', '${item.userId}')">${item.userId}</Button>`;
    return item;
  });

  const col = [];
  for (let i = 0; i < data.length; i++) {
    for (let key in data[i]) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }
  }

  //Add edit and delete header
  //   col.push("Edit","Delete");

  // CREATE DYNAMIC TABLE.
  const table = document.createElement("table");

  // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

  let tr = table.insertRow(-1); // TABLE ROW.

  for (let i = 0; i < col.length; i++) {
    const th = document.createElement("th"); // TABLE HEADER.
    th.innerHTML = col[i];
    tr.appendChild(th);
  }

  // ADD JSON DATA TO THE TABLE AS ROWS.
  for (let i = 0; i < data.length; i++) {
    tr = table.insertRow(-1);

    for (let j = 0; j < col.length; j++) {
      const tabCell = tr.insertCell(-1);
      tabCell.innerHTML = data[i][col[j]];
    }
  }

  // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
  const divContainer = document.getElementById("myData");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
}

appendData(data);
<!DOCTYPE html>
<html>
  <body>
    <div id ="myData"></div>
  </body>
</html>

Related