0
我從商店的「物品」被存儲在會話中的唯一數組中,並在購物車上傳遞,並且我想爲每個物品提供數量,如果我想要從購物車刪除項目以從陣列中刪除。我爲「加號」和「減號」製作了html表單和數量按鈕,但是我無法弄清楚如何在按鈕更改輸入時捕捉輸入值,然後將其與每個項目的成本相乘,以便稍後我可以得到總成本(在代碼中可以看出,我爲每個項目設置了值=「1」,因此每個項目的基值爲1)。我還與JS作出刪除,我想,但也已刪除項目的行didnt弄清楚如何從陣列中刪除該項目數量和刪除購物車中的物品
這是我的購物車:
<div class="container">
<div class="jumbotron">
<div class="container text-center">
<h3>Shopping Cart</h3>
<table class="table table-striped" >
<tr>
<th class="items" > Product </th>
<th class="items"> Quantity </th>
<th class="items"> Unit Price </th>
<th>Total Cost</th>
<th></th>
</tr>
<?php foreach ($selectedItems as $item): ?>
<tr>
<th class="items"><?= $item->name ?></th>
<th class="items ">
<div>
<button type="button" class="sub" title="If u want less quantity">-</button>
<input type="text" value="1" id="quantity" class="quantity" name="quantity[]" onchange="quantityChange(this)" >
<button type="button" class="add" title="If u want more quantity" >+</button>
</div>
</th>
<th id="price" class="items"> <?= $item->price ?></th>
<th><span class="allcost"> </span></th>
<th class="items">
<button class="remove_field " title="Click to delete product" >
<div class="glyphicon glyphicon-trash" ></div>
</button>
</th>
</tr>
<?php endforeach; ?>
</table>
<?= Html::a('Return to Shop', ['/stock/shop'], ['class' => 'btn btn-default']) ?>
<?= Html::a('Checkout', ['/stock/checkout'], ['class' => 'btn btn-default']) ?>
</div>
</div>
<script type="text/javascript">
$(document).on('click', 'button.remove_field', function() {
$(this).closest('tr').remove();
});
$('.add').click(function() {
var target = $('.quantity', this.parentNode)[0];
target.value = +target.value + 1;
target.onchange();
});
$('.sub').click(function() {
var target = $('.quantity', this.parentNode)[0];
if (target.value > 1) {
target.value = +target.value - 1;
}
target.onchange();
});
function quantityChange(sender) {
var quantity = $(sender).val();
console.log(quantity);
};
我ActionCart:
public function actionCart() {
Yii::$app->session->open();
Yii::$app->session->open();
$selectedItems = Yii::$app->session['selectedItems'];
$stockItems = Stock::find()->where(['id' => $selectedItems])->all();
$data = [
'selectedItems' => $stockItems,
];
return $this->render('cart', $data);
}