Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    May 2016
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Storing table of arrays as links using JSON and local storage

    New to JS, and I'm not sure what I'm doing wrong. I have a table which i create dynamically, it stores a persons information as objects in a array, which is stored as a link + table row. I'm lost as to how to store the table with the links of information for each person, using local storage. When I reload the page I need to still be able to click on a row and have the form loaded with the object data.

    -screen-shot-2016-05-12-7-38-10-pm-png

    The HTML
    Code:
        <div id="results">
            <h1>Actors</h1>
            <table id="actorsTable" class="table table-hover">
            </table>
        </div> <!-- end results-->



    Here is the addActor function, where I dynamically create the table, and table rows of object arrays.

    Code:
    
    var addActor = function() {
        // Assigning Form values to variables
        var firstN = $("#fName").val();
        var lastN = $("#lName").val();
        var birthdate = $("#birthDate").val();
        var gender = $("[name='gender']:checked").val();
        var action = $("#action").prop('checked');
        var comedy = $("#comedy").prop('checked');
        var drama = $("#drama").prop('checked');
        var sciencefiction = $("#sciencefiction").prop('checked');
        var horror =$("#horror").prop('checked');
        var suspense = $("#suspense").prop('checked');
    
        // creates newActor variable that contains an object for each input value
        var newActor = {fName: firstN, lName: lastN, birthDate: birthdate, gender: gender, action: action, comedy: comedy, drama: drama, suspense: suspense, sciencefiction: sciencefiction, horror: horror}
    
        // Creates a table of links for each added actor  with an id based from # of actors
        $("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this); updateActor(this);' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
    
        actors.push(newActor);
    
        alert(JSON.stringify(newActor));
    
        $(".update").off("click");
        $(".update").on("click", selectActor);
    
        console.log(actors);
    
        localStorage.setItem('actors', JSON.stringify(actors));
    
    };

    Here is what I've attempted to try and get the stored information back to the site.

    Code:
    $(window).unload(function () {
       localStorage.getItem('actors');
    });
    
    $(document).ready(function() {
        $( "#birthDate" ).datepicker();
    
        actorState ("new");
    
        $("#addNewActor").click(function() {
            if(validateForm()==true)
            {
                addActor();
                clearForm(actorForm);
            }
        });
    
    });

    Here is all the code in a fiddle/pen of the program working.

  2. #2
    Regular Coder
    Join Date
    Feb 2016
    Posts
    128
    Thanks
    0
    Thanked 32 Times in 32 Posts
    What's still missing is reloading the actors from local storage. Define a new function:
    Code:
                var addActorsOnLoad = function () {
                    var json_actors = localStorage.getItem('actors');
                    if (json_actors) {
                        actors = JSON.parse(json_actors);
                        for (var i = 0; i < actors.length; i++) {
                            // Creates a table of links for each added actor
                            $("#actorsTable").append("<tr><td><a href='' class='update' data-idx='" + i + "'>" + actors[i].fName + " " + actors[i].lName + "</a></td></tr> ");
                        }
                        $(".update").off("click");
                        $(".update").on("click", selectActor);
                    }
                };
    and call it on document-ready:
    Code:
                $(document).ready(function () {
                    addActorsOnLoad();

  3. Users who have thanked Sempervivum for this post:

    zzzian (05-13-2016)

  4. #3
    New to the CF scene
    Join Date
    May 2016
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks for the reply.

    I had to make a few changes to how I was using local storage with the objects in the table rows. With what I originally posted it was only storing the latest 'added' row, instead of every row that was added. I found out by running to console.

    Heres what I changed it to.

    Code:
    var addActor = function() {
        var newActor = {fName: firstN, lName: lastN, birthDate: birthdate, gender: gender, action: action, comedy: comedy, drama: drama, suspense: suspense, sciencefiction: sciencefiction, horror: horror}
    
        // Creates a table of links for each added actor  with an id based from # of actors
        $("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this); updateActor(this);' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
    
        actors.push(newActor);
    
        alert(JSON.stringify(newActor));
    
        $(".update").off("click");
        $(".update").on("click", selectActor);
    
        console.log(actors);
        localStorage.setItem("lsActor", JSON.stringify(actors));
    };

    Code:
    
    $(document).ready(function() {
        var newActors2 = localStorage.getItem("lsActor")
        console.log('newActors2', JSON.parse(newActors2));
    });
    This would output each actor added as an object to the console

    Attachment 15761




    Now, I updated my code with your function, and works so thank you. I was a bit lost as to how to load the stored objects back into the table, but the for loop makes sense now that I see how its done.



    One part I have a question on.... I added the onclick='deleteActor(this)' to the <a> and it deletes it from the table, but not from storage. So with that, do I have to create another function to delete the row in storage, as I deleted it from the table? Or can I just do it in the deleteActor() function.


    Here is my attempt to figure out how to delete from local storage, as well as the table. Now it deletes already from the table just fine. But when I refresh the page it's still there. Not sure, but I think i have to get the key of the local storage I want to delete, and somehow link it with the row I've selected to delete?

    Code:
    var deleteActor = function(e) {
        // unbinds the delete actor button click, so you can delete multiple rows
        $("#deleteActor").unbind();
        $("#deleteActor").on('click', function(event) {
            event.preventDefault();
    
            var lsRow = JSON.parse(localStorage["lsActor"]);
            for (var i=0; i < lsRow.length; i++) {
                if (lsRow[i]) {
                    lsRow.removeItem(lsRow);
                    break;
                }
            }
    
            var row = e.parentNode.parentNode;
            row.parentNode.removeChild(row);
            clearForm(actorForm);
            actorState("new");
        });
    };
    
    
    
    var addActor = function() {
        // Assigning Form values to variables
        var firstN = $("#fName").val();
        var lastN = $("#lName").val();
        var birthdate = $("#birthDate").val();
        var gender = $("[name='gender']:checked").val();
        var action = $("#action").prop('checked');
        var comedy = $("#comedy").prop('checked');
        var drama = $("#drama").prop('checked');
        var sciencefiction = $("#sciencefiction").prop('checked');
        var horror =$("#horror").prop('checked');
        var suspense = $("#suspense").prop('checked');
    
        // creates newActor variable that contains an object for each input value
        var newActor = {fName: firstN, lName: lastN, birthDate: birthdate, gender: gender, action: action, comedy: comedy, drama: drama, suspense: suspense, sciencefiction: sciencefiction, horror: horror}
    
        // Creates a table of links for each added actor  with an id based from # of actors
        $("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this); updateActor(this);' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
    
        // pushes newActor into the end of actors array
        actors.push(newActor);
    
        alert(JSON.stringify(newActor));
    
        $(".update").off("click");
        $(".update").on("click", selectActor);
    
        console.log(actors);
    
    
        localStorage.setItem("lsActor", JSON.stringify(actors));
    
    };
    
    
    var addActorsOnLoad = function () {
        var json_Actors = localStorage.getItem("lsActor");
        if (json_Actors) {
            actors = JSON.parse(json_Actors);
            for (var i = 0; i < actors.length; i++) {
                // Creates a table of links for each added actor  with an id based from # of actors
                $("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this); updateActor(this);' class='update' data-idx='" + i + "'>" + actors[i].fName + " " + actors[i].lName + "</a></td></tr> ");
            }
            $(".update").off("click");
            $(".update").on("click", selectActor);
    
        }
    };
    
    
    $(document).ready(function() {
        addActorsOnLoad();
        
        $( "#birthDate" ).datepicker();
    
        actorState ("new");
        
    
        var newActors2 = localStorage.getItem("lsActor")
        console.log('newActors2', JSON.parse(newActors2));
    
    
        $("#addNewActor").click(function() {
            if(validateForm()==true)
            {
                addActor();
                clearForm(actorForm);
            }
        });
    
    
        $("#updateActor").click(function() {
            if(validateForm()==true)
            {
                updateActor();
                clearForm(actorForm);
            }
        });
    
        $("#deleteActor").click(function() {
            deleteActor();
            localStorage.removeItem(actors[i]);
        });
    
        $("#clearButton").click(function () {
            clearForm(actorForm);
        });
    
    });

    Sorry for the wall of text, and thanks for your help again!

    Codepen of the whole code

  5. #4
    Regular Coder
    Join Date
    Feb 2016
    Posts
    128
    Thanks
    0
    Thanked 32 Times in 32 Posts
    You save the complete array "actors" in you local storage. Therefore you cannot delete a single row but you will have to store the new entire array again. That's quite easy and sufficient.
    Another option would be saving each field in the array in one specific entry, e. g. "Actor0", Actor1". Then you would be able to delete a specific entry. However IMO it's easier and sufficient saving the complete array as you do now.


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •