2

I have 2 fiddles.

  • In the first one (JSFiddle 1) I create a new table and save into localStorage

  • In the second one (JSFiddle 2) I created a copy row feature (selected row and copied it to the selected table).

My goal is to combine both fiddles into one, that allows you to:

  • Add new table [Available on JSFiddle 1]
  • When adding Table, there is a 'copy to table 1' option [Available on JSFiddle 2]
  • Can select row, then copy it in selected table using that option. [Available on JSFiddle 2]

I need to delete this, and replace it with the new table feature, using code $('#table' + localStorage.Index).dataTable({...})

 $('#table2').dataTable({
    "data": localStorage.getItem('dataSet_table2') ? JSON.parse(localStorage.getItem('dataSet_table2')) : [], //changed here
    "columns": [{
      "title": "First Name"
    }, {
      "title": "Last Name"
    }, {
      "title": "Action"
    }],
    "bStateSave": true,
    "stateSave": true,
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": false,
    "bInfo": false,
    "bAutoWidth": false
  });

I've spent a lot of time on this but I have some problems:

  • I can't choose row for the second time when it is reloaded.
  • Can't copy row.

My Working Fiddle [UPDATED 2] : https://jsfiddle.net/59u53rvn/2/

var mainTable = $("#mainTable").dataTable({
  "bStateSave": true,
  "stateSave": true,
  "bPaginate": false,
  "bLengthChange": false,
  "bFilter": false,
  "bInfo": false,
  "bAutoWidth": false
});

/*SELECT OPTION */
mainTable.on('click', 'tr', function() {
  var $row = $(this),
    isSelected = $row.hasClass('selected')
  $row.toggleClass('selected')
    .find(':checkbox').prop('checked', !isSelected);
});

$('#copyToTable1,#copyToTable2').on('click', function() {

  let $elem = $(this);
  var table = $("#table" + $elem.attr('id').replace(/[a-zA-Z]/ig, ''));
  var tbl_id = table.attr('id');

  var $row = mainTable.find(".selected");
  if (!$row.length) {
    console.log('You must select some rows to copy first');
    return;
  } else {
    var r = confirm("Copy to table " + tbl_id + "?");
    var table_to_copy = table.dataTable();
    if (r == true) {
      copyRows(mainTable, table_to_copy);
      console.log("Copied!");
      setTimeout('console.clear()', 2000);
    }
  }
});

function copyRows(fromTable, toTable) {
  var $row = fromTable.find(".selected"),
    storageName = 'dataSet_' + toTable.attr('id'), //added this line 
    dataSet = localStorage.getItem(storageName) ? JSON.parse(localStorage.getItem(storageName)) : []; //added this line 

  $.each($row, function(k, v) {
    if (this !== null) {
      addRow = fromTable.fnGetData(this);
      toTable.fnAddData(addRow);
      dataSet.push(addRow); //added this line 
    }
  });

  localStorage.setItem(storageName, JSON.stringify(dataSet)); //added this line 
}

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = '<button id="copyToTable' + localStorage.Index + '" >copyToTable ' + localStorage.Index + '</button>' +
      '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
      '<div class="zf-table">' +
      '<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade dynamicTable">' +
      '<thead>' +
      '<tr>' +
      '<th>Audience Name</th>' +
      '<th>Type</th>' +
      '</tr>' +
      '</thead><tbody></tbody>' +
      '</table>' +
      '</div>' +
      '</div>';
    return addTable;
  }

  if (true) {
    /** INDEX FOR INCREMENT ID **/
    if (typeof(Storage) !== "undefined") {
      if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
      } else {
        localStorage.Index = 1;
      }
    } // if storage

    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    let newtableHTML = getTableList();
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultFolder array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

    /* append Table baru */
    $('.tab-content').append(newtableHTML);
    var newTable = $("#table" + localStorage.Index).dataTable({
      "data": localStorage.getItem('dataSet_table' + localStorage.Index) ? JSON.parse(localStorage.getItem('dataSet_table' + localStorage.Index)) : [], //changed here
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });
    alert("sucess create table");

  } else {
    alert("Failed create Table");
  }
}); // submitButton func


//on init fill the table-content
$(document).ready(function() {

  var resultTable = JSON.parse(localStorage.getItem("tableList"));
  if (resultTable != null) {
    //get the nav reference in DOM
    let tableContent = $(".tab-content");

    //clear the html contents
    tableContent.html('');

    for (var i = 0; i < resultTable.length; i++) {
      var items = resultTable[i];
      $(".tab-content").append(items.table);
    }
    $(".dynamicTable").dataTable({
      "data": localStorage.getItem('dataSet_table' + localStorage.Index) ? JSON.parse(localStorage.getItem('dataSet_table' + localStorage.Index)) : [], //changed here
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });
  } else {
    let inititalTable = [];
    inititalTable.push({
      table: $('div.tab-content').html()
    });
    localStorage.setItem("tableList", JSON.stringify(inititalTable));
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>

<input type="button" class="submitButton" value="ADD NEW TABLE">

<div class="tab-content">
  <div class="tab-pane" id="mainFolder">
    <h3>DEFAULT TABLE</h3>
    <div class="zf-table">
      <table id="mainTable" class="table table-bordered table-hover myFade">
        <thead>
          <tr>
            <th>Audience Name</th>
            <th>Type</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Calvin</td>
            <td>Lookalike</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

</div>

Ask whatever I have not explained to this question, I will fix it here and in the fiddle.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
Calvin Ananda
  • 1,440
  • 1
  • 14
  • 30
  • 1
    This seems like "write code for me" sort of question. You have a better chance of receiving a good answer if you isolate the problem and ask about that instead. – Gyrocode.com Dec 29 '17 at 15:33
  • I've made the code, I make 2 options. but I can't combine it, and this is my last task to solve it. – Calvin Ananda Dec 29 '17 at 16:47

1 Answers1

1

Okay, I'm using your code 2 as the starting point to merge your code 1 with code 2.

See working example:

https://jsfiddle.net/mgsrzzye/1/

First, we need to check local storage on page load then, if exist print the tables on page.

$(document).ready(function(){
        var localtbl = localStorage.getItem('tableList');

    var resultTable = [];
    if(localtbl !== undefined && localtbl !== ''){
    resultTable = JSON.parse(localtbl);
    }
        $.each(resultTable, function(i,v){
                $('#table1_wrapper').append(v.table);

    $('table[id^="table'+(i+2)+'"]').dataTable({
      "data": localStorage.getItem('dataSet_table' + (i+2)) ? JSON.parse(localStorage.getItem('dataSet_table' + (i+2))) : [], //changed here
      "columns": [{
        "title": "First Name"
      }, {
        "title": "Last Name"
      }, {
        "title": "Action"
      }],
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });

      })
})

Then, we need copy the code 1 for adding the new table with some changes.

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {

  var tblcount = ($('table[id^="table"]').length + 1);

    var addTable = '<br><button class="btn btn-success" id="copyToTable'+tblcount+'"> Copy To Table '+(tblcount)+'</button>' +
    '<h3 style="color:red;">Table '+(tblcount)+'</h3>' +
      '<table id="table'+tblcount+'" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>';
    var getTbl = localStorage.getItem("tableList");
    var resultTable = [];
    if(getTbl !== undefined && getTbl !== ''){
    resultTable = JSON.parse(getTbl);
    }
    let newtableHTML = addTable;
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultFolder array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

  //console.log(tblcount);
  $('#table' + (tblcount-1) + '_wrapper').after(addTable);

  $('#table' + (tblcount)).dataTable({
    "data": localStorage.getItem('dataSet_table' + tblcount) ? JSON.parse(localStorage.getItem('dataSet_table' + tblcount)) : [], //changed here
    "columns": [{
      "title": "First Name"
    }, {
      "title": "Last Name"
    }, {
      "title": "Action"
    }],
    "bStateSave": true,
    "stateSave": true,
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": false,
    "bInfo": false,
    "bAutoWidth": false
  });


}); // submitButton func

The last one, we need to use body as sometimes we added dynamic table.

$('body').on('click', 'button[id^="copyToTable"]', function(){
  let $elem = $(this);
  var table = $("#table" + $elem.attr('id').replace(/[a-zA-Z]/ig, ''));
  var tbl_id = table.attr('id');

  var $row = mainTable.find(".selected");
  if (!$row.length) {
    console.log('You must select some rows to copy first');
    return;
  } else {
    var r = confirm("Copy to table " + tbl_id + "?");
    var table_to_copy = table.dataTable();
    if (r == true) {
      copyRows(mainTable, table_to_copy);
      console.log("Copied!");
      setTimeout('console.clear()', 2000);
    }
  }
})
DennisFrea
  • 1,112
  • 8
  • 10
  • Can you explain the point of this code `id ^`? `'button[id^="copyToTable"]'` – Calvin Ananda Dec 30 '17 at 05:18
  • 1
    It will trigger to all buttons start with id copyToTable, eg: copyToTable2, copyToTable3 etc – DennisFrea Dec 30 '17 at 06:29
  • It's a way to create shorter selector in jquery so you dont need to write $('#copyToTable2, #copyToTable3, #copyToTable3').click(function... So it will be faster to code & more simple also good for dynamic elements/ incremental elements. Check docs here https://api.jquery.com/attribute-starts-with-selector/ or here an explanation in stackoverflow https://stackoverflow.com/questions/23223526/jquery-selector-for-id-starts-with-specific-text – DennisFrea Dec 30 '17 at 08:23
  • I added it for testing purpose to clear all the tables inside the localstorage – DennisFrea Dec 31 '17 at 00:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162234/discussion-between-ananda-and-dennisfrea). – Calvin Ananda Dec 31 '17 at 00:22