Saving Table data in LocalStorage

2019-05-26 13:23发布

问题:

  $('.new_customer').click(function () {
    var table = $("table");
    var number = table.find('tr').length;
    table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" value="Save" id="save' + number + '"></td></td>' +
        '<td><input type="text"/></td>' +
        '<td><input type="text"/></td>' +
        '<td><input type="text"/></td><td><input type="text"/></td>' +
        '<td><input type="text"/></td><td><input type="text"/></td><td><input type="text"/></td>' +
        '<td><input type="text"/></td></tr>');
    $(document).on('click', 'input[id^="save"]', function () {
        $(this).parents('tr').children('td').each(function () {
            if ($(this).children("input[type=button]").length==0) {
                $(this).html($(this).children('input').val());
            }
            else{
                $("input[type=button]").removeClass("btn-success").addClass("btn-warning").val("review");
            }
        });

    });
});

Good Day! I am creating table with some information, which I want to save in localStorage. I am just a beginner and I have never done this thing before, could you help me? I tried to use something like that, but this code is invalid. I will be glad of any help. thank you.

         var inputs= $("tr").children('input').val();
        localStorage.setItem("customer", JSON.stringify(inputs));

回答1:

Local storage only accepts string data. You would need to create a json array of the data, then parse it when retrieving it.

http://jsfiddle.net/ha6kdhp7/

<input value="1"/>
<input value="2"/>
    <input value="3"/>

    var myArray = new Array();
var inputs = $('input').each(function(index, i){
    myArray.push($(this).val())
});


//console.log(myArray);
        localStorage.setItem("customer", JSON.stringify(myArray));
console.log($.parseJSON(localStorage.getItem("customer")));