ASP.NET C# jQuery实现POS系统:商品加载并添加至HTML表格/购物车求助
Hey there! Let's tackle adding those products to your POS system's cart table using jQuery. I'll walk you through the steps clearly, building on the server-side code you already have.
First, let's polish up your HTML structure to make it easy for jQuery to interact with, then write the JavaScript logic to handle adding items (and updating quantities if the product is already in the cart).
Step 1: Complete Your Product Display & Cart Table HTML
First, let's finish the product cards with necessary data attributes and add a dedicated cart table:
<div class="content-top"> <h1> Recent Products</h1> <div class="content-top1"> <% if (products_list.Count > 0) { foreach (var prod in products_list) { %> <div class="col-md-3 col-md2"> <div class="col-md1 simpleCart_shelfItem"> <!-- Product info (customize this to match your product fields) --> <img src="<%= prod.ImagePath %>" alt="<%= prod.Name %>" class="product-img" /> <h3 class="product-name"><%= prod.Name %></h3> <p class="product-price">$<%= prod.Price %></p> <!-- Add to cart button with data attributes for product details --> <button class="add-to-cart btn btn-success" data-prod-id="<%= prod.Id %>" data-prod-name="<%= prod.Name %>" data-prod-price="<%= prod.Price %>"> Add to Cart </button> </div> </div> <% } } %> </div> </div> <!-- Shopping Cart Table --> <div class="cart-section mt-4"> <h2>Your Cart</h2> <table id="cart-table" class="table table-striped"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Subtotal</th> <th>Actions</th> </tr> </thead> <tbody id="cart-body"> <!-- Dynamic cart items will be inserted here --> </tbody> <tfoot> <tr> <td colspan="3" class="text-right fw-bold">Total:</td> <td id="cart-total">$0.00</td> <td></td> </tr> </tfoot> </table> </div>
Step 2: jQuery Logic to Handle Cart Actions
Add this script (either in a <script> tag at the bottom of your page or a separate JS file):
$(document).ready(function() { // Handle "Add to Cart" button clicks $('.add-to-cart').on('click', function() { // Grab product data from the button's attributes const prodId = $(this).data('prod-id'); const prodName = $(this).data('prod-name'); const prodPrice = parseFloat($(this).data('prod-price')); // Check if the product is already in the cart const existingItemRow = $('#cart-body tr[data-prod-id="' + prodId + '"]'); if (existingItemRow.length) { // Product exists: increment quantity and update subtotal const quantityInput = existingItemRow.find('.quantity-input'); let currentQty = parseInt(quantityInput.val()); currentQty++; quantityInput.val(currentQty); const newSubtotal = (prodPrice * currentQty).toFixed(2); existingItemRow.find('.subtotal').text('$' + newSubtotal); } else { // Product is new: create a new table row const newCartRow = ` <tr data-prod-id="${prodId}"> <td>${prodName}</td> <td>$${prodPrice.toFixed(2)}</td> <td><input type="number" class="quantity-input" value="1" min="1" style="width: 60px;"></td> <td class="subtotal">$${prodPrice.toFixed(2)}</td> <td><button class="remove-item btn btn-danger btn-sm">Remove</button></td> </tr> `; $('#cart-body').append(newCartRow); // Bind events to the new row's elements bindCartRowEvents(); } // Update the cart's total price updateCartTotal(); }); // Helper function to bind events to cart row elements (for dynamic rows) function bindCartRowEvents() { // Handle quantity changes $('.quantity-input').off('change').on('change', function() { const row = $(this).closest('tr'); const price = parseFloat(row.find('td:nth-child(2)').text().replace('$', '')); const qty = parseInt($(this).val()); const subtotal = (price * qty).toFixed(2); row.find('.subtotal').text('$' + subtotal); updateCartTotal(); }); // Handle item removal $('.remove-item').off('click').on('click', function() { $(this).closest('tr').remove(); updateCartTotal(); }); } // Helper function to calculate and update the cart's total function updateCartTotal() { let total = 0; $('#cart-body .subtotal').each(function() { const subtotal = parseFloat($(this).text().replace('$', '')); total += subtotal; }); $('#cart-total').text('$' + total.toFixed(2)); } });
Key Features Explained
- Data Attributes: We use
data-prod-*attributes to store product details directly on the "Add to Cart" button, making it easy for jQuery to fetch without parsing text. - Duplicate Handling: The code checks if a product is already in the cart and increments its quantity instead of adding a duplicate row.
- Dynamic Event Binding: The
bindCartRowEventsfunction ensures that new rows (added after page load) have working quantity and remove buttons. - Price Formatting:
toFixed(2)ensures all prices display with two decimal places, which is critical for POS systems.
This should give you a fully functional way to add products to your cart table with jQuery!
内容的提问来源于stack exchange,提问作者Farmanullah




