如何将数据库JSON数据回显到jQuery生成的发票动态字段?
Here's a practical, step-by-step implementation to populate your dynamic invoice fields with stored JSON data:
1. Prepare the Stored Data
First, ensure your backend passes the saved invoice items (as a JSON array) to the frontend. For example, embed it directly in a script tag (adjust based on your backend language):
<script> // This data is pulled from your database (e.g., via PHP, Node.js, etc.) const storedInvoiceItems = <?= json_encode($invoiceItemsFromDB) ?>; </script>
2. Define Reusable Functions
Create modular functions to handle row creation and event handling (tweak the HTML structure to match your existing fields):
Function to Add a Dynamic Item Row
This function generates a new row, optionally pre-filled with stored data:
function addItemRow(itemData = null) { // Replace this HTML with your actual row structure const rowHtml = ` <div class="item-row mb-2"> <div class="col-sm-4"> <input type="text" name="description[]" class="form-control description" placeholder="Item Description" value="${itemData ? itemData.description : ''}"> </div> <div class="col-sm-2"> <input type="number" name="quantity[]" class="form-control quantity" min="1" value="${itemData ? itemData.quantity : 1}"> </div> <div class="col-sm-2"> <input type="number" name="price[]" class="form-control price" step="0.01" value="${itemData ? itemData.price : 0.00}"> </div> <div class="col-sm-2"> <input type="number" name="total[]" class="form-control total" readonly value="${itemData ? itemData.total : 0.00}"> </div> <div class="col-sm-2"> <button class="btn btn-xs btn-danger tableaction" data-action="remove"> <i class="fa fa-fw fa-trash"></i> Remove </button> </div> </div> `; // Append the row to your container (update selector to match your HTML) $('.invoice-items-container').append(rowHtml); // Attach event listeners to the new row attachRowEventListeners(); }
Function to Attach Event Listeners
This ensures quantity/price changes update the total, and remove buttons work as expected:
function attachRowEventListeners() { // Calculate total when quantity or price changes $('.quantity, .price').off('input').on('input', function() { const $row = $(this).closest('.item-row'); const quantity = parseFloat($row.find('.quantity').val()) || 0; const price = parseFloat($row.find('.price').val()) || 0; $row.find('.total').val((quantity * price).toFixed(2)); }); // Remove row when delete button is clicked $('[data-action="remove"]').off('click').on('click', function() { $(this).closest('.item-row').remove(); }); }
3. Initialize Fields on Page Load
In your document ready handler, load stored data and set up the add button:
$(document).ready(function() { // Add new empty row when "Add More Items" is clicked $('[data-action="add"]').on('click', function() { addItemRow(); }); // Populate stored items if available if (storedInvoiceItems && storedInvoiceItems.length > 0) { storedInvoiceItems.forEach(item => { addItemRow(item); }); } else { // Add one empty row if no stored data exists addItemRow(); } });
Key Notes
- Match Your HTML: Adjust the
rowHtmlinaddItemRowto exactly match the dynamic rows your existing code generates. - Data Consistency: Ensure the keys in
storedInvoiceItems(likedescription,quantity) align with your field names. - Event Cleanup: Using
.off()before.on()prevents duplicate event listeners when adding multiple rows. - Backend Integration: Confirm your backend correctly fetches the stored JSON data and passes it to the frontend (e.g.,
json_encodein PHP).
内容的提问来源于stack exchange,提问作者Nitin mehra

