1

I want to append table data that I have saved in local storage. I have tried this loop to add in its cells and loop through changing the numbers based on the count or rows it reads. here is my JS code:

$(function() {
    $("#loadTask").change(function() {
        var task = loadTaskFromStorage1($("#loadTask").val());
        var rows = $('#items-table tr').length;

        var loop = 0;
        var r = 1;

        while (loop < rows) {
            $("#items-table").append('<tr>'
          +'<td>'+task.cells[r][0]+'</td>'
          +'<td>'+task.cells[r][1]+'</td>'
          +'<td>'+task.cells[r][2]+'</td>'
          +'<td>'+task.cells[r][3]+'</tr>')
          r += 1;
          loop += 1;
        }

    })
})

this obviously does not work since im guessing when I JSON.Stringify the table data it saves it into one long string becuase when I added alert(row); before and after the loop I got 1 everytime even though the task had two rows.

Here is what I use to append the data into the table which I later save in local storage using a special name so I can save multiple different table datas :

function addRow() {
    var item_text = $('#item-input').val();
    var item_color = $('#color-input').val();
    var size_text = $('#sizes-item').val();
    var any_color = $('#any-color').is(':checked') ? 'Any Color' : '';
    var any_size = $('#any-size').is(':checked') ? 'Any Size' : '';
    $('#items-table').append('<tr>'
        +'<td>'+item_text+', '+item_color+'</td>'
        +'<td>'+size_text+'</td>'
        +'<td>'+any_color+', '+any_size+'</td>'
        +'<td><button class="remove-btn"><div class="thex">X</div></button><td>'
        +'</tr>');
}

$(function(){
  $('#add-item').click(function(){
    addRow();
    return false;
  });
  $('body').on('click', '.remove-btn', function(){
    $(this).parent().parent().remove();
  });
});

I thought that maybe since it wont count the table rows properly the only real thing that doesnt change at any table row is the remove button that gets added with every row.

So it tried changing

var rows = $('#items-table tr').length;

to:

var rows = $('#items-table button').length;

which I thought would work but when I added the alert part before and after the loop I got 0 every time.

What could I do to be able to count each row somehow to be able to append them properly back into the table the same way they were added in.

here is the javascript that saves the table data into localStorage:

$(function() {

  loadAllTasks();

  $("#addTask").click(function() {
    let cells = Array.prototype.map.call($("#items-table")[0].rows, row => {
      return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
    });
    // create task object from cells
    var task = {
      cells: cells
    };

    var itemCount = $("#items-table tr").length - 1;

    var lengthrows = {
      itemCount: itemCount
    }

    saveLength(lengthrows);

    var rowsCount = loadLength()
    alert(rowsCount);

    // set name property of the task
    task.Name = $("#taskName").val();

    // call save method using the new task object
    saveTaskInStorage(task);
  });

  function saveTaskInStorage(task) {
    // Get stored object from localStorage
    var savedTasks = JSON.parse(localStorage.getItem('tasks'));

    // To be sure that object exists on localStorage
    if (!savedTasks || typeof(savedTasks) !== "object")
      savedTasks = {};

    // Set the new or exists task by the task name on savedTasks object
    savedTasks[task.Name] = task;

    // Stringify the savedTasks and store in localStorage
    localStorage.setItem('tasks', JSON.stringify(savedTasks));

    alert("Task has been Added");
  }

 function saveLength(lengthrows) {
    var count = localStorage.getItem('lengthrows');
    if (!count || typeof(count) !== "object")
      savedCount = {};
    savedCount[task.Name] = task;
    localStorage.setItem('itemCount', savedTasks);
  }
  function loadLength(taskName) {
    var lengthCount = localStorage.getItem("itemCount");
      return lengthCount[taskName];
  }

  function loadAllTasks() {

    // Get all saved tasks from storage and parse json string to javascript object
    var savedTasks = JSON.parse(localStorage.getItem('tasks'));

    // To be sure that object exists on localStorage
    if (!savedTasks || typeof(savedTasks) !== "object")
      return;

    // Get all property name of savedTasks object (here it means task names)
    for (var taskName in savedTasks) {
      $("#loadTask").append('<option>' + taskName + '</option>')
    }
  }

});

function loadTaskFromStorage1(taskName) {
   var savedTasks = JSON.parse(localStorage.getItem('tasks'));

    //Return the task by its name (property name on savedTasks object)
    return savedTasks[taskName];
}

I am also trying to save the count of the rows in each specific task. The stuff I attempted below with the saveLength doesn't work any suggestions?

Any help is appreciated Thank You <3

  • 1
    Can you give us code which saves data to `localStorage`? – ya.ymer Aug 23 '18 at 23:28
  • check now @ya.ymer –  Aug 23 '18 at 23:34
  • Sorry for late answer. Your code works for me perfectly - each row storing in local Storage and accessible. Can you include full your code (with html)? ([jsfiddle](https://jsfiddle.net/yaymer/2btmrcys/3/)) – ya.ymer Aug 24 '18 at 00:39
  • It looks weird on JS fiddle could I email you the code? my email is wojprod@gmail.com if u don't want to share your email on stack overflow email me please so I could email you back the code –  Aug 24 '18 at 00:59
  • I've sent an email to you. – ya.ymer Aug 24 '18 at 01:03
  • I still have not received it you can try maxym4726@gmail.com aswell or you could tell me your email @ya.ymer –  Aug 24 '18 at 01:17
  • i've sent, check. – ya.ymer Aug 24 '18 at 01:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178651/discussion-between-ya-ymer-and-developer12). – ya.ymer Aug 24 '18 at 01:56
  • Ive created a temporary solution It works but It might bring in a lot of bugs I changed rows = 99; it works but Im not sure how stable it is –  Aug 24 '18 at 02:01

1 Answers1

1

Your code when you need load task might be looks like that:

$(function() {

  $("#loadTask").change(function() {
    var task = loadTaskFromStorage1($("#loadTask").val());
    var rows = task.cells;
    let tpl = (rows) => {
      return rows.slice(1).map(e => '<tr>' + e.map(e => `<td>${e}</td>`) + '</tr>');
    }
    $("#items-table").append(tpl(rows));

  })
})

For removing tasks you need to add removeTask function which i've wrote:

function removeTask (taskName) {
    var tasks = JSON.parse(localStorage.getItem('tasks'));

    if (typeof tasks !== "object")
        return false; // our tasks list not set. return negative.

    delete tasks[taskName];
    $('#loadTask > option:contains(' + taskName + ')').remove();
    localStorage.setItem('tasks', JSON.stringify(tasks));
    return true;
};

And modify your click listener at .remove-btn. Your listener should be look like that:

$('body').on('click', '.remove-btn', function(){
    $(this).parent().parent().remove();

   if ($('#items-table > tbody').children().length < 2) {
    console.log("attemping to remove...");
    if (removeTask($("#loadTask").val()))
        alert('Task successfully removed.');
   }
  });
ya.ymer
  • 676
  • 4
  • 17
  • wow works great, any ideas on how I would be able to remove the task from storage by clicking the remove buttons which does remove the row. something like if there are no rows left then remove the task from local storage? –  Aug 24 '18 at 02:50
  • where do I add this stuff on my js file? on the top where I have the remove stuff or move it to the bottom after the saved task stuff –  Aug 24 '18 at 03:11
  • function after `addRow`, listener - you to need change your. – ya.ymer Aug 24 '18 at 03:13
  • IT WORKS THANKS YOU GENIUSSSSS –  Aug 24 '18 at 03:23
  • 1
    Have a nice day! ;) – ya.ymer Aug 24 '18 at 03:27
  • Do I have your permission to use this in a closed source project? –  Sep 05 '18 at 06:06
  • @developer12, sure. You can use this code everywhere you want. – ya.ymer Sep 05 '18 at 15:41
  • I want to add in a counter that counts how many table rows there are in the table i created this var itemCount = $("#items-table tr").length I want to be able to do task.itemCount and it will tell me how many rows there are. so I can call that in another js file –  Sep 07 '18 at 15:03
  • @developer12 you can, but you need declare this variable before using in other file. e.g. in file which loaded before your "other" file. – ya.ymer Sep 07 '18 at 15:34
  • were would I put it? could you add it into your answer? Because I don't know were to put it so it would be specific for each saved task –  Sep 07 '18 at 16:32
  • You can read [this](https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file) answer. – ya.ymer Sep 07 '18 at 17:26
  • I have made several attemps on how to do this and I still cant get it to work I want to be able to do task.count and then that along with the task.cells will be specific for the loaded task from storage I made an edit on my question and would really appreciate it if you could take a look at it and maybe fix it for me??? –  Sep 07 '18 at 22:36
  • can you give me information about errors in the console? – ya.ymer Sep 08 '18 at 08:32