简体   繁体   中英

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.

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. Im saving the product id as the id of a div so that its easier to find the variable.

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. 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

 $('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 attributes are supposed to be unique.

In your javascript, you should have used the this keyword which refers to the selected HTML object. The item variable then become:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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