简体   繁体   English

Laravel & Javascript 购物车数量问题

[英]Laravel & Javascript shopping cart qty problem

I'm making and online shop and I'm stuck at the shopping cart part.我正在制作和在线商店,但我被困在购物车部分。 I want to have a select where the user selects the quantity of the product.我想要一个 select ,用户可以在其中选择产品的数量。

I'm using javascript for monitoring changes on the selected option and to save the id of the product to then make a request etc etc and get the cart updated.我正在使用 javascript 来监视所选选项的更改并保存产品的 ID,然后发出请求等并更新购物车。 Im saving the product id as the id of a div so that its easier to find the variable.我将产品 id 保存为 div 的 id,以便更容易找到变量。

The problem that I have is that my console log shows that it only selects the first item on the cart (and its product id) but not the rest of the cart products.我遇到的问题是我的控制台日志显示它只选择购物车上的第一项(及其产品 ID),而不选择购物车产品的 rest。 this is the view这是视图

@foreach ($products as $product)

    <div class="carrito-item" >

        <img src="../public/images/{{$product['item']['image']}}" alt="" class="carrito-item__image">

        <div class="carrito-item__text">

            <div class="carrito__box carrito__box--name">
                <p class="carrito-item__name">{{ $product['item']['name'] }}</p>
            </div>
            <div class="carrito__box carrito__box--qty" id="<?= $id?>">
                <p class="carrito-item__cantidad" >x {{ $product['qty'] }}</p>

                <select name="qty" id="qty" >

                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>

                </select>
            </div>

        </div>
    </div>
@endforeach

And this is the JS file这是JS文件

 $('select').on('change', function(){

    var item=$('#qty').closest(".carrito__box--qty");
    var id= item.attr("id");
                
    console.log(item);
    console.log(id);      
               
 });  

     

Should be:应该:

var item=$(this).closest(".carrito__box--qty");

instead of代替

var item=$('#qty').closest(".carrito__box--qty");

You are using a non-unique id #qty in a loop which is a wrong approach.您在循环中使用了非唯一 id #qty ,这是一种错误的方法。 Id attributes are supposed to be unique. Id属性应该是唯一的。

In your javascript, you should have used the this keyword which refers to the selected HTML object.在您的 javascript 中,您应该使用this关键字,它指的是所选的 HTML object。 The item variable then become: item变量然后变为:

var item=$(this).closest(".carrito__box--qty");

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

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