build unique table with JQuery AJAX

Viewed 74

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.

The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table

JSON1:

[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]

JSON2:

[{"GLComment":"comment from table 2","EnComment":""},
 {"GLComment":"","EnComment":""}]

I have tried doing this to append to my existing table

var tblSomething = document.getElementById("table1");

<table class="table 1">
  <thead>
    <th id = "white">GL Comment</th>
    <th id = "white">En Comment</th>
  </thead>
</table>

//table does not get built here only for table 1
<table class="table 2">
      <thead>
        <th id = "white">GL Comment</th>
        <th id = "white">En Comment</th>
      </thead>
</table>

<script>
//this only works for table1
$(document).ready(function() {
  infoTableJson = {}
  buildInfoTable();
});

function buildInfoTable(){
  $.ajax({ //allows to updates without refreshing
    url: "comment1.json", //first json file
    success: function(data){

      data = JSON.parse(data)
      var tblSomething = '<tbody>';

      $.each(data, function(idx, obj){

        //Outer .each loop is for traversing the JSON rows
        tblSomething += '<tr>';

        //Inner .each loop is for traversing JSON columns
        $.each(obj, function(key, value){
          tblSomething += '<td data-key="' + key + '">' + value + '</td>';
        });
        //tblSomething += '<td><button class="editrow"></button></td>'
        tblSomething += '</tr>';
      });
      tblSomething += '</tbody>';
      $('.table').append(tblSomething)
$('.table td').on('click', function() {
             var row = $(this).closest('tr')
             var index = row.index();
      
             var comment = row.find('td:nth-child(1)').text().split(',')[0]
             var engcomment = row.find('td:nth-child(2)').text().split(',')[0]

             var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
             var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
      
              var newDialog = $("<div>", {
                 id: "edit-form"
               });
      
      
             newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
             newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
      
             //  JQUERY UI DIALOG
             newDialog.dialog({
               resizable: false,
               title: 'Edit',
               height: 350,
               width: 350,
               modal: true,
               autoOpen: false,
               buttons: [{
                 text: "Save",
                 click: function() {
      
                console.log(index);
                user = $.cookie('IDSID')
                var today = new Date();
                var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
                var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                var dateTime = date+' '+time;
                //FIXME
                    
                var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
                var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
      
                   row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
                   row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
                  // update data
      
                  data[index].GLComment = comment;
                  data[index].EngComment =engcomment;
      
                   $.ajax({
                       type: "POST",
                       url: "save.asp",
                       data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
                       success: function(){},
                       failure: function(errMsg) {
                           alert(errMsg);
                       }
                   });
                   $(this).dialog("close");
                   $(this).dialog('destroy').remove()
      
                 }
               }, {
                 text: "Cancel",
                 click: function() {
                   $(this).dialog("close");
                   $(this).dialog('destroy').remove()
                 }
               }]
             });
             //$("body").append(newDialog);
             newDialog.dialog("open");
      
      
           })
      
      
           },
           error: function(jqXHR, textStatus, errorThrown){
           alert('Hey, something went wrong because: ' + errorThrown);
           }
           });
        }
      
        </script>
1 Answers

The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.

$(document).ready(function() {

  // call the function and pass the json url
  buildInfoTable("comment1.json");
  buildInfoTable("comment2.json");
  
  
  // Just to disable the snippet errors for this demo
  // So the ajax aren't done
  // No need to run the snippet :D
  $.ajax = ()=>{}
  
});

function buildInfoTable(jsonurl){
  $.ajax({
    url: jsonurl,
    success: function(data){

      data = JSON.parse(data)
      
      // Clone the prebuild table
      // and remove the prebuild class
      var dynamicTable = $(".prebuild").clone().removeClass("prebuild"); 

      // Loop the json to create the table rows
      $.each(data, function(idx, obj){
        rows = '<tr>';
        $.each(obj, function(key, value){
          rows += '<td data-key="' + key + '">' + value + '</td>';
        });
        rows += '</tr>';
      });

      // Append the rows the the cloned table
      dynamicTable.find("tbody").append(rows)
      
      // Append the cloned table to document's body
      $("body").append(dynamicTable)
    }
  })
}
</script>
/* This class hides the prebuid table */
.prebuild{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
  <thead>
    <th id = "white">GL Comment</th>
    <th id = "white">En Comment</th>
  </thead>
  <tbody>
  </tbody>
</table>

Related