4 Leave Cover 4 Leave Cover - 3 years ago 199
HTML Question

Repopulate table rows dynamically from localstorage

I have a problem populating the table rows given the data from localstorage (at STEP 3). Currently I have two buttons to add/remove row(s) in the Remarks section below, can I reuse that?

However, below are my scenario:

STEP 1 By default there will be table HTML code as shown below, user can add new rows or delete selected rows. Upon Save button clicked, it will save the data into localstorage (code below):

<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="myModal-label" aria-hidden="true">
<input type="button" value="Add row" onClick="addRow('dyn_table')" />
<input type="button" value="Remove row" onClick="deleteRow('dyn_table')" />
<div class="form-group">
<table class="table" id="dyn_table">
<tbody><tr><td><input type="checkbox" class="big-checkbox" name="chk[]" checked="checked" /></td>
<td>
<div class="form-group">
<label for="dyn_payment_method">Payment Method</label>
<select name="dyn_item_code[]" class="dyn_item_code form-control">
<option disabled="" selected="" value=""> -- select an option -- </option>
<option value="cash">Cash</option>
<option value="cheque">Cheque</option>
<option value="tt">TT</option>
<option value="cc">Credit Card</option>
</select>
</div>
<div class="form-group">
<label for="dyn_amount">Amount</label>
<input type="number" pattern="[0-9].[0-9]" class="dyn_amount" name="dyn_amount[]" step="0.01">
</div>
<div class="form-group">
<label for="dyn_reference">Reference Number</label>
<input type="text" class="dyn_reference" name="dyn_reference[]" class="form-control" >
</div>
</td>
</tr>
</tbody>
</table>
</div>
<button type="submit" class="btn btn-success" id="btnSave">Save</button>
</div>

<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Company</th>
<th>Invoice No.</th>
<th>Due Date</th>
<th>Invoice Amount</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>ABC Inc.</td>
<td>I0001</td>
<td>2020-01-01 00:00:00</td>
<td>USD100</td>
<td>ACTIVE</td>
<td><a href="#" data-id="5" data-toggle="modal" data-target="#edit-modal"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</a></td>
</tr>
</tbody>
</table>


STEP 2 This is the code to save all the rows into localstorage (setter)

$('#btnSave').on('click', function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var mykey = 'set'+id;
var my_table = [];

$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();

my_table.push([checkbox, itemcode ,amount, reference]);
});

localStorage.setItem(mykey, JSON.stringify(my_table));

});


STEP 3 This is the code to retrieve the data from localstorage (getter), but the problem is how to repopulate the table rows?

$('#edit-modal').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget).data('id'); //id from edit button
var mykey = 'set'+id;

$('#btnSave').attr('data-id' , id);

if(localStorage.getItem(mykey)==null){
console.log('key not found');
} else {
console.log('key found');

var lsSetFields = JSON.parse(localStorage.getItem(mykey));
var checkbox,itemcode,amount,reference = '';

$.each( lsSetFields, function( key, value ) {
checkbox = value[0];
itemcode = value[1];
amount = value[2];
reference = value[3];

console.log('checkbox='+checkbox);
console.log('itemcode='+itemcode);
console.log('amount='+amount);
console.log('reference='+reference);

// I guess must be doing the table re-populating here,
// Should I remove all rows then repopulate or ???
});
}
});


Remarks

function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;

}
}

function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
console.log(chkbox);
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Please remain minimum ONE row. The last row is now preserved.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}

Answer Source

You can modify Step 3 as follows and should solve the issue. I have updated comments in the code below.

$('#edit-modal').on('show.bs.modal', function (e) {
    var id = $(e.relatedTarget).data('id'); //id from edit button
    var mykey = 'set' + id;

    $('#btnSave').attr('data-id', id);

    if (localStorage.getItem(mykey) == null) {
        console.log('key not found');
    } else {
        console.log('key found');

        var lsSetFields = JSON.parse(localStorage.getItem(mykey));
        var checkbox, itemcode, amount, reference = '';

        $("#dyn_table tr").not(":first").remove(); //Delete all rows except first

        $.each(lsSetFields, function (key, value) {
            //Clone first row and update input and select fields
            $("#dyn_table tr:first").clone().find("input, select").each(function (index) {
                if (index === 0) $(this).prop("checked", value[index]);
                $(this).val(value[index]);
            }).end().appendTo("#dyn_table");
        });

        //Delete first row
        $("#dyn_table tr:first").remove();
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download