我将商店中的“项目”存储在会话中的唯一数组中并传递到购物车中,我想为每个项目输入数量,如果我想从购物车中删除要删除的项目数组。我为“加号”和“减号”制作了 html 表单和数量按钮,但我不知道如何在输入值随按钮更改时捕获输入值,然后将其乘以每个项目的成本,所以稍后我可以获得总成本(在代码中可以看出我为每个项目设置了 value="1",因此每个项目的基值为 1)。我还用 JS 从我想要的已删除项目中删除了行,但也没有弄清楚如何从数组中删除项目
这是我的购物车:
<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);
};
我的行动车:
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);
}