简体   繁体   English

使用 jQuery/Javascript 获取并求和动态和多元素的值

[英]Get and SUM the value of dynamic and multiple element using jQuery/Javascript

I have a list of product in a cart.我在购物车中有一个产品列表。 Now, i want to calculate all of the product price in cart.现在,我想计算购物车中的所有产品价格。 But i still didn't get how to get and calculate the value from dynamic element.但我仍然不知道如何从动态元素中获取和计算值。 Here's my code for the dynamic product in a cart:这是我的购物车中动态产品的代码:

<div class="modal fixed-right fade" id="modalShoppingCart" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-vertical" role="document">
    <div class="modal-content">
      <ul class="list-group list-group-lg list-group-flush">
        <?php 
          $no = 1;
          $query = mysqli_query($con, "SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price FROM cart AS c LEFT JOIN product AS p ON c.product_id= p.id LEFT JOIN user AS u ON c.user_id=u.id WHERE c.product_id = p.id GROUP BY p.id")or die(mysqli_error($con));

          while($data = mysqli_fetch_array($query)){
            $product_id = $data['product_id'];
            $sql  = mysqli_query($con, "SELECT COUNT(product_id) FROM cart WHERE product_id='$product_id' GROUP BY product_id ");

            $row = mysqli_fetch_array($sql);
            $quantity = $row['COUNT(product_id)'];

            $sale_price = (int)$data['sale_price'] * $quantity;
        ?>
        <li class="list-group-item">
          <div class="row align-items-center">
            <div class="col-4">
              <a href="product.html">
                <img class="img-fluid" src="../assets/img/<?php echo $data['thumbnail']; ?>" alt="...">
              </a>
            </div>
            <div class="col-8">
              <p class="font-size-sm font-weight-bold mb-6">
                <a class="text-body" href="product.php"><?php echo $data['name']; ?></a> <br>
                <span class="text-muted"><?php echo 'Rp'.(str_replace(',', '.', number_format($sale_price))) ?? 'Rp0'; ?></span>
                <input type="hidden" name="sale_price" class="sale_price<?php echo $no++; ?>" value="<?php echo $sale_price; ?>">
              </p>
              <div class="d-flex align-items-center">
                <input type="number" class="d-inline-block form-control form-control-xxs w-auto m-width-65" name="quantity" value="<?php echo $quantity; ?>">
                <a class="font-size-xs text-gray-400 ml-auto" href="hapus-produk-cart.php?id=<?php echo $data['id']; ?>">
                  <i class="fe fe-x"></i> Hapus
                </a>
              </div>
            </div>
          </div>
        </li>
        <?php } ?>
      </ul>

      <div class="modal-footer line-height-fixed font-size-sm bg-light mt-auto">
        <strong>Total</strong> <strong class="ml-auto"></strong>
      </div>

      <div class="modal-body">
        <a class="btn btn-block btn-dark" href="checkout.php">Checkout Pesanan</a>
      </div>
    </div>
  </div>
</div>

since the products is dynamic, i didn't know how to get the value in <input type="hidden" name="sale_price" class="sale_price<?php echo $no++; ?>" value="<?php echo $sale_price; ?>"> .由于产品是动态的,我不知道如何获取<input type="hidden" name="sale_price" class="sale_price<?php echo $no++; ?>" value="<?php echo $sale_price; ?>"> . and how to calculate it using jQuery or javascript.以及如何使用 jQuery 或 javascript 进行计算。 Would u help me how to do that?你能帮我怎么做吗? I really need your help guys.我真的需要你们的帮助。 Thank you in advance.先感谢您。

Where to start?从哪儿开始? I am not going to deal with the need to use prepared statements but I suggest you do some reading about SQL injection.我不打算处理使用准备好的语句的需要,但我建议您阅读有关 SQL 注入的内容。 So, let's try starting with your first query -所以,让我们尝试从您的第一个查询开始 -

SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price
FROM cart AS c
LEFT JOIN product AS p ON c.product_id= p.id
LEFT JOIN user AS u ON c.user_id=u.id
WHERE c.product_id = p.id
GROUP BY p.id

Why the LEFT joins?为什么左派加入? These should be INNER joins, surely?这些应该是 INNER 连接,当然? Why join to the user table at all if it is not being returned in the SELECT list?如果 SELECT 列表中没有返回用户表,为什么还要加入用户表? This current query is going to return all carts with their respective products and users.此当前查询将返回所有购物车及其各自的产品和用户。 Probably not what you intended.可能不是你想要的。 Maybe you want the cart and associated products for the current user?也许您想要当前用户的购物车和相关产品? I will continue on this basis.我将在此基础上继续。

SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price, c.quantity * p.sale_price AS line_item_total
FROM cart AS c
JOIN product AS p ON c.product_id= p.id
WHERE c.user_id = ? /* where ? is the current user's id */

I have taken the liberty of modifying the query to get the db to return the line_item_total for us.我冒昧地修改了查询以让数据库为我们返回 line_item_total。

And now onto the second query, run for each record returned by first query -现在进入第二个查询,为第一个查询返回的每条记录运行 -

SELECT COUNT(product_id)
FROM cart
WHERE product_id='$product_id'
GROUP BY product_id

I am not quite sure what this is supposed to be doing but it won't work as you expect.我不太确定这应该做什么,但它不会像你期望的那样工作。 It will return the COUNT of users who have this product_id in their cart.它将返回购物车中有此 product_id 的用户的 COUNT 个。 The only relevant quantity should be the one already returned by your cart query.唯一相关的数量应该是您的购物车查询已经返回的数量。

This is definitely not beautiful but it should be enough to get you started -这绝对不漂亮,但它应该足以让你开始 -

<?php

$current_user_id = 1; // coming from session or ...

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('host', 'user', 'pass', 'db');

$sql = 'SELECT c.id, c.quantity, c.product_id, p.name, p.thumbnail, p.sale_price, c.quantity * p.sale_price AS line_item_total
FROM cart AS c
JOIN product AS p ON c.product_id = p.id
WHERE c.user_id = ?';

$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 'i', $current_user_id);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);
$cart_items = mysqli_fetch_all($result, MYSQLI_ASSOC);

?>

<div class="modal fixed-right fade" id="modalShoppingCart" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-vertical" role="document">
        <div class="modal-content">
            <ul class="list-group list-group-lg list-group-flush">
                <?php $cart_total = 0; foreach ($cart_items as $cart_item): ?>

                    <li class="list-group-item cart-item">
                        <span class="cart-item-img"><img src="../assets/img/<?php echo $cart_item['thumbnail']; ?>"></span>
                        <span class="cart-item-name"><?php echo $cart_item['name']; ?></span>
                        <span class="cart-item-price"><?php echo $cart_item['sale_price']; ?></span>
                        <span class="cart-item-quantity"><input type="number"  name="quantity[<?php echo $cart_item['product_id']; ?>]" value="<?php echo $cart_item['quantity']; ?>"></span>
                        <span class="cart-item-total"><?php echo $cart_item['line_item_total']; ?></span>
                    </li>

                <?php $cart_total += $cart_item['line_item_total']; endforeach; ?>
            </ul>

            <div class="modal-footer line-height-fixed font-size-sm bg-light mt-auto">
                <strong>Total</strong> <span id="cart-total-price" class="ml-auto"><?php echo $cart_total; ?></span>
            </div>

            <div class="modal-body">
                <a class="btn btn-block btn-dark" href="checkout.php">Checkout Pesanan</a>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('.cart-item-quantity input').change(function() {
        updateQuantity(this);
    });

    /* Update quantity */
    function updateQuantity(quantityInput) {
        /* Calculate line price */
        var productRow = $(quantityInput).closest('li.cart-item');
        var price = parseFloat(productRow.find('span.cart-item-price').text());
        var quantity = $(quantityInput).val();
        var linePrice = price * quantity;
        productRow.find('span.cart-item-total').text(linePrice.toFixed(2));
        updateCart();
    }

    function updateCart() {
        var cartTotal = 0;
        $('span.cart-item-total').each(function () {
            cartTotal += parseFloat($(this).text());
        });
        $('span#cart-total-price').text(cartTotal.toFixed(2));
    }
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM