我能够显示名称,价格并获取先前输入数据库的数量。在页面加载时,我希望脚本通过将每个选定项目的价格和数量相乘并相加每个项目的小计来得出总计,从而计算出总计。

我怎样才能做到这一点?

<div class="panel_container"></div>

<script type="text/javascript">
    $( document ).ready(function() {

    @foreach ($items->products as $product)
        var product = $('#{!! $product->id !!}');
        var selectedItems = JSON.parse(product.attr('data-products'));

        if(product.prop("checked") )  {
            $('.panel_container').append(
                '<div class="container">' +
                    '<p class="name">' + product.name + '</p>' +
                    '<p class="price" data-price="' + product.price + '">' + product.price + '</p>' +
                    '<p class="sub-total"><span class="sub-total" name="sub-total" id="sub-total"></span></p>'+
                    '<input type="text" class="form-control quantity"  placeholder="qty" name="quantity[]" value="{!!$product->pivot->quantity!!}" required/>'+
                '</div>'

            )

        } else {
            //clear selected item
       }
    @endforeach

    calculate();
});

var sub-total = 0;
var calculate = function() {
    var ship_container = $('.panel_container').closest('div');
    var quantity = Number($('.quantity').val());
    var price = Number($('.panel_container').closest('div').find('.price').data('price'));

    ship_container.find(".sub-total span").text(quantity * price);

}

</script>

最佳答案

必须修改您的代码才能为每种产品运行。

var grandTotal = 0;
var calculate = function() {

  // for each product
  $('.panel_container .container').each(function() {
    var product = $(this),
      quantity = Number(product.find('.quantity').val()), // get quantity
      price = Number(product.find('.price').data('price')), // get price
      total = quantity * price; // calculate product total

    product.find('.sub-total span').text(total); // show product total
    grandTotal += total; // add to grand total
  });

  // use the grandTotal here..
  alert('Grand total: ' + grandTotal);
}


此外,id属性在html中必须唯一,因此您应从循环中删除id="sub-total"

关于javascript - 如何计算页面加载时所选项目的成本-JS和Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47731771/

10-09 01:12