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

9
  • 1
    Can you give us code which saves data to localStorage? Commented Aug 23, 2018 at 23:28
  • check now @ya.ymer Commented Aug 23, 2018 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) Commented Aug 24, 2018 at 0:39
  • It looks weird on JS fiddle could I email you the code? my email is [email protected] if u don't want to share your email on stack overflow email me please so I could email you back the code Commented Aug 24, 2018 at 0:59
  • I've sent an email to you. Commented Aug 24, 2018 at 1:03

1 Answer 1

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.');
   }
  });
Sign up to request clarification or add additional context in comments.

13 Comments

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?
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
function after addRow, listener - you to need change your.
IT WORKS THANKS YOU GENIUSSSSS
Have a nice day! ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.