Add Row Function Not Working

Add Row Function Not Working

zgoforthzgoforth Posts: 167Questions: 5Answers: 0

So I am trying to expand my table to where I can add rows of data to it. I added a button, and a function to add values to the table, but when I implement it into the script editor on SharePoint the DataTable doesn't appear, just the header and footer.

What I added:
<input type="button" value="add" id="addbtn" />
$('#addbtn').click(addrow);

function addrow() {
    $('#myTable').dataTable().fnAddData( [
        $('#Program').val(),
        $('#Deliverable').val(),
        $('#To').val(),
        $('#Date').val(),
        $('#Approved').val(),
        $('#Notes').val()
        ] );

}

Here is my full code, I will link a test case in the comments after I make it as I need to use static data instead of the sharepoint ajax request.

<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class="header">
  <h1><strong>Deliverables</strong></h1>
  <p><strong>Click the Program/Deliverable names to Collapse/Expand the rows</strong></p>
</div>
<input type="button" value="add" id="addbtn" />
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
  <thead class="thead-dark">
    <tr>
      <th>Program</th>
      <th>Deliverable</th>
      <th>To</th>
      <th>Date</th>
      <th>Approved</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tfoot class="thead-dark">
  <tr>
      <th>Program</th>
      <th>Deliverable</th>
      <th>To</th>
      <th>Date</th>
      <th>Approved</th>
      <th>Notes</th>
    </tr>
  </tfoot>
</table>
</div>
<style> //These are just CSS styling I chose to use.
.btn-dark {
    color: #fff;
    background-color: #343a40;
    border-color: #343a40;
}
div.container {
    min-width: 980px;
    margin: 0 auto;
}
.header {
  padding: 10px;
  text-align: center;
}
body {
    font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
    margin: 0;
    padding: 0;
    color: #333;
    background-color: #fff;
}
div.dt-button-collection {
    position: static;
}
</style>
<script>
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
    //create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests

var urls = ["url1","url2","url3","url4","url5","url6","url7","url8"];
       
    for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
      $.ajax({
        url: urls[i],
        'headers': { 'Accept': 'application/json;odata=nometadata' },
        success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
          data = data;
          var table = $('#myTable').DataTable();
          table.rows.add( data.value ).draw();
        }
      }); 
    }
}
$(document).ready(function() {
    var collapsedGroups = {}; 
    var top = '';
    var parent = '';
    
  var table = $('#myTable').DataTable( {
  $('#addbtn').click(addrow);
    "columns": [
      { "data": "Program", visible: false },
      { "data": "Deliverable", visible: false },
      { "data": "To" },
      { "data": "Date" },
      { "data": "Approved" },
      { "data": "Notes" }
    ],
    
    dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
     buttons: [{
      extend: 'collection',
      className: "btn-dark",
      text: 'Export',
      buttons:
      [{
      extend: "excel", className: "btn-dark"
    },
      {
      extend: "pdf", className: "btn-dark"
    },
       {
      extend: "print", className: "btn-dark"   
    },
      ],
    }],
    order: [[0, 'asc'], [1, 'asc'] ],   
    rowGroup: {
            dataSrc: [
            'Program',
            'Deliverable'
            ],
            startRender: function (rows,group,level){
                var all;
                if (level === 0) {
                    top = group;
                    all = group;
                } else if (level === 1) {
                    parent = top + group; 
                    all = parent; 
                    // if parent collapsed, nothing to do
                    if (!collapsedGroups[top]) {
                        return;
                    }                   
                } else {
                    // if parent collapsed, nothing to do
                    if (!collapsedGroups[parent]) {
                        return;
                    } 
                    all = top + parent + group;
                }

                var collapsed = !collapsedGroups[all];
                console.log('collapsed:', collapsed);
              
              rows.nodes().each(function(r) {
                r.style.display = collapsed ? 'none' : '';
              });
              //Add category name to the <tr>.
              return $('<tr/>')
                .append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
                .attr('data-name', all)
                .toggleClass('collapsed', collapsed);
                
            
            }
            
        }
  } );
  function addrow() {
    $('#myTable').dataTable().fnAddData( [
        $('#Program').val(),
        $('#Deliverable').val(),
        $('#To').val(),
        $('#Date').val(),
        $('#Approved').val(),
        $('#Notes').val()
        ] );

}
    
 loadData();

 $('#myTable tbody').on('click', 'tr.dtrg-start', function () {
        var name = $(this).data('name');
        collapsedGroups[name] = !collapsedGroups[name];
        table.draw(false);
    });     
} );
</script>

Replies

  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    but when I implement it into the script editor on SharePoint the DataTable doesn't appear, just the header and footer.

    Did you look at your browser's console for errors?

    Kevin

  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    BTW, $('#myTable').dataTable().fnAddData( is the legacy version of row.add(). You would be better off using the current syntax.

    Kevin

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    @kthorngren Uncaught TypeError: Cannot read property 'add' of undefined
    This is the error I get

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    I placed it in the loadData function

     for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
          $.ajax({
            url: urls[i],
            'headers': { 'Accept': 'application/json;odata=nometadata' },
            success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
              data = data;
              var table = $('#myTable').DataTable();
              $('#addbtn').on( 'click', function () {
                myTable.row.add([
            $('#Program').val(),
            $('#Deliverable').val(),
            $('#To').val(),
            $('#Date').val(),
            $('#Approved').val(),
            $('#To').val()      
        ]).draw();
    });
              table.rows.add( data.value ).draw();
            }
          }); 
        }
    }
    
  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    $('#addbtn').on( 'click', function () {

    You don't want to create an event handler inside a loop. If you do then that event run run once for each iteration through the loop. Move it into document.ready().

    Add this line to the event handler:
    var myTable = $('#myTable').DataTable();

    Before myTable.row.add([.

    Kevin

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    So I did what you said

    $(document).ready(function() {
              $('#addbtn').on( 'click', function () {
              var myTable = $('#myTable').DataTable();
            $('#Program').val(),
            $('#Deliverable').val(),
            $('#To').val(),
            $('#Date').val(),
            $('#Approved').val(),
            $('#To').val()     
        ]).draw();
    
        var collapsedGroups = {}; 
        var top = '';
        var parent = '';
        
      var table = $('#myTable').DataTable( {
        "columns": [
          { "data": "Program", visible: false },
          { "data": "Deliverable", visible: false },
          { "data": "To" },
          { "data": "Date" },
          { "data": "Approved" },
          { "data": "Notes" }
        ],
    

    And I get an error Uncaught SyntaxError: Unexpected token ']'
    When I click on the link to send me to the error it is just blank, I do not understand

  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    You are missing myTable.row.add([.

    Kevin

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    Uncaught SyntaxError: Unexpected end of input

    I input it here -

    $(document).ready(function() {
              $('#addbtn').on( 'click', function () {
              var myTable = $('#myTable').DataTable();
    myTable.row.add ([
            $('#Program').val(),
            $('#Deliverable').val(),
            $('#To').val(),
            $('#Date').val(),
            $('#Approved').val(),
            $('#To').val()    
        ]).draw();
    
  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    I guess you are missing a closing parenthesis ) or bracket } somewhere. if you want to post a link to your page or a test case we can take a look.

    Kevin

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    @kthorngren will do. I went to https://social.technet.microsoft.com/wiki/contents/articles/31995.sharepoint-2013-working-with-rest-api-using-jquery-ajax.aspx and I am pretty sure I found a partial solution. to send the data with a post. It is completely irrelevant because I still don't have a function to add new items to the DataTable as I still have no idea how...

    function sendData() {
        var urls = ["url1","url2","url3","url4","url5","url6","url7","url8"];
           
        var data1 = {
               Program: 'Please provide the Program name here',
               Deliverable: 'Please provide the type of deliverable here',
               To: 'Please provide the recipients email here',
               Date: 'Please provide the submission date here',
               Approved: 'Please provide where or not the deliverable has been approved here',
               Notes: Please provide notes about the deliverable here'
        };
         $.ajax({
            for (i=0; i < urls.length; i++) {
            $.ajax({
                       url: urls[i],
                       method: "POST",
                                     data: JSON.stringify(data),
                       headers: { "Accept": "application/json; odata=verbose",
                                       "X-RequestDigest": $("#__REQUESTDIGEST").val()                                  
                       },
                       success: function (data) {
                                  alert('Item added successfully');
                      },
                      error: function (error) {
                          alert("Error: "+ JSON.stringify(error));
                     }
              });
            }
        });
    }
    

    If you see the code I supplied at the top of this discussion, I place this sendData() at the very bottom. Is this correct?

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    https://jsfiddle.net/4euzm8qn/ need to create static data to populate into the table but aside from that there your go

  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449
    edited September 11

    You are getting this error in the browser's console:

    editor_console=true:283 Uncaught SyntaxError:

    Clicking on the line number it pulls up this line:

               Notes: Please provide notes about the deliverable here'
    

    You are missing an opening ' before Please. Is this what you are wanting help with? If so please work on these types of errors on your own. These are not Datatables issues and take time away from helping with other threads.

    Kevin

  • zgoforthzgoforth Posts: 167Questions: 5Answers: 0

    @kthorngren I told you I have the sendData down which is unrelated to the DataTable. I still am having trouble grasping how to write new rows to the table

  • kthorngrenkthorngren Posts: 10,722Questions: 25Answers: 2,449

    This example show the approach I would take - which is similar to the way Editor data exchanges work.
    http://live.datatables.net/qeyenibi/1/edit

    This example does not use a server script to save the data to the DB so this part is simulated. But basically you get the new row data from the user, post it to the server, the server script saves it then fetches it and returns the fetch result. Then use row.add() to add the row to the table. This way the user sees what is in the database which might be different than what they entered.

    Kevin

Sign In or Register to comment.