I have built an application that takes user input and adds the values to a table on submit. I wanted to integrate an undo button that removes the most recent item that was added from the table. Here is the form to get the user input and the table:
<form method="post" action="" id="myForm">
<!-- gets the store code from URL -->
<?php $store = $_GET['store']; ?>
<!-- Store input -->
<label for="store">Store: </label>
<input name="store" type="hidden" id="store" value="<?php echo $store; ?>">
<?php echo $store; ?>
<br><br>
<!-- Employee input -->
<label for="employee">Employee: </label>
<input name="employee" id="employee" type="text" maxlength="3" value="<?php echo isset($_POST['employee']) ? $_POST['employee'] : '' ?>"><br><br>
<!-- Product input -->
<label for="product">Product: </label>
<input name="product" id="product" type="text" placeholder="Product SKU" maxlength="12">
<label for="productQuantity">Quantity: </label>
<input name="productQuantity" id="productQuantity" type="number" value="1">
<input name="add" id="add" type="submit" value="Add" onClick="addRow()">
<br><br>
<input name="undo" id="undo" type="submit" value="Undo" onClick="undoRow('screen');"><br><br>
<input name="clear" id="clear" type="submit" value="Clear All" onClick="deleteRows()"><br><br>
<button name="submit" type="submit" onClick="deleteRows()">Submit</button>
</form>
<!-- Table for displaying items added -->
<div id="table" style="overflow-x: auto">
<table style="width: 300px">
<thead>
<tr>
<th>Employee</th>
<th>Product</th>
<th>Qty</th>
</tr>
</thead>
<tbody id="screen">
</tbody>
</table>
</div>
Here are the JS functions:
<script>
// displays local storage key=data on page load
$( document ).ready(function(){
$('#screen').html(localStorage.getItem("data"));
});
// appends user input to html table
function addRow(){
var str = '<tr class = "boxType">
<td>'+$('#employee').val()+'</td>
<td>'+$('#product').val()+'</td>
<td>'+$('#productQuantity').val()+'</td>
</tr>';
$('#screen').append(str);
localStorage.setItem("data", $('#screen').html());
}
// removes the last row from table
function undoRow(screen){
var table = document.getElementById('screen');
var rws = table.getElementsByTagName('TR');
table.removeChild(rws[rws.length-1]);
}
// deletes rows from table
function deleteRows(){
localStorage.clear();
$('#screen').empty();
}
</script>
My idea was to rewrite the addRow function that creates a new local storage item on each submit, and then have the undoRow function delete the most recent local storage key. Unfortunately, I am having trouble figuring out how to do this. Any help would be appreciated.