Skip to content
Advertisement

How to save table content permanently

I am an absolute beginner in javascript. I tried to make an table which can save the content i type in it. I just got the total opposite from what i wanted the table deletes the content everytime i refresh the website.

Basically my question is what i have to change so i can save the data permantly and it dont vanish everytime i refresh the webpage. Also it would nice to know what i did wrong. I already tried to change some things but it got just worse

Here is some example code for you:

JS:

    $(document).ready(function () {
    var counter = 0;

    $("#addrow").on("click", function () {
        var newRow = $("<tr>");
        var cols = "";

        cols += '<td><input type="text" class="form-control" name="name' + counter + '"/></td>';
        cols += '<td><input type="text" class="form-control" name="mail' + counter + '"/></td>';
        cols += '<td><input type="text" class="form-control" name="phone' + counter + '"/></td>';

        cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger "  value="Delete"></td>';
        newRow.append(cols);
        $("table.order-list").append(newRow);
        counter++;
    });



    $("table.order-list").on("click", ".ibtnDel", function (event) {
        $(this).closest("tr").remove();       
        counter -= 1
    });


});



function calculateRow(row) {
    var price = +row.find('input[name^="price"]').val();

}

function calculateGrandTotal() {
    var grandTotal = 0;
    $("table.order-list").find('input[name^="price"]').each(function () {
        grandTotal += +$(this).val();
    });
    $("#grandtotal").text(grandTotal.toFixed(2));
}

Basic HTML:

<div class="container">
<table id="myTable" class=" table order-list">
<thead>
    <tr>
        <td>name</td>
        <td>mail</td>
        <td>phone</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="col-sm-4">
            <input type="text" name="name" class="form-control" />
        </td>
        <td class="col-sm-4">
            <input type="mail" name="mail"  class="form-control"/>
        </td>
        <td class="col-sm-3">
            <input type="text" name="phone"  class="form-control"/>
        </td>
        <td class="col-sm-2"><a class="deleteRow"></a>

        </td>
    </tr>
</tbody>
<tfoot>
    <tr>
        <td colspan="5" style="text-align: left;">
            <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
        </td>
    </tr>
    <tr>
    </tr>
</tfoot>

Advertisement

Answer

You can use the localStorage object, which stores data with no expiration date. This data will not be deleted when you refresh the page or even close the browser. In order to do that, you first need to create the function which will save the data into localStorage.

function save_data(){
    let table_data = []
    $('.form-control').each(function() { table_data.push( $(this).val() )});
    localStorage.setItem('table_data', JSON.stringify(table_data));
}

This function iterates through all table cells and saves its content into table_data array. Then table_data array is converted into String with JSON.stringify and saved in localStorage. This function should be executed every time you add, remove or edit one of the rows. In order to do that we need to create new event handlers:

$('tbody').on("DOMSubtreeModified", function() {save_data()});
$('tbody').on('change', '.form-control', function() {save_data()});

The first one triggers save_data function every time a row is created or removed. The second one saves data whenever the table’s content is modified.

We also need a function for loading data from localStorage:

function load_data(){
    let table_data = JSON.parse(localStorage.getItem('table_data'));
    for (i = 1; i < table_data.length/3; i++) $("#addrow").click()
    $('.form-control').each(function(index) {$(this).val(table_data[index])});
}

This function loads data from localStorage using getItem function. The loaded data is a String, so it is converted into the array using JSON.parse. Next, new rows are inserted according to the size of table_data array. In the end, it iterates through all table cells and fills them with loaded data. This function should be executed only after you the page is loaded and only if data exists in localStorage.The best way is to put this line at the bottom of ready function:

if (localStorage.getItem("table_data") != null) load_data()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement