Osama Mohammed
Osama Mohammed

Reputation: 2861

problem with updating counter with jquery inside loop with django

everything is working correctly, except when clicking the increment or decrement buttons, only the last product on the cart is updated!!!, for other carts, I can update the value manually and click the button it will updated without any problem !!!

this is the code for .html in django

{% for item in cart %}
                            <div class="card rounded-3 mb-4 ">
                                <div class="card-body p-4">
                                    <div class="row d-flex justify-content-between align-items-center">
                                        <div class="col-md-2 col-lg-2 col-xl-2">
                                            <img
                                                    src="{{ item.product.product_image.url }}"
                                                    class="img-fluid rounded-3" alt="Cotton T-shirt">
                                        </div>
                                        <div class="col-md-3 col-lg-3 col-xl-3">
                                            <p class="lead fw-normal mb-2">{{ item.product.name }}</p>
                                            <p><span class="text-muted">
                    {% if item.product.is_service %}
                        Service
                    {% else %}
                        Product
                    {% endif %}
                </span> <span class="text-muted">
                                        </div>
                                        <div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data">
                                            <input type="hidden" value="{{ item.product_id }}" class="prod_id">
                                            {% csrf_token %}
                                            {% if item.product.is_service == False %}
                                                {% if item.product.quantity >= item.product_quantity %}

                                                    <div class="container">
                                                        <div class="row">
                                                            <div class="col-lg-2">
                                                                <div class="input-group">
                                    <span class="input-group-btn">
                                        <button type="button" id="quantity-left-minus"
                                                class="  changeQuantity btn btn-primary btn-number"
                                                data-type="minus">
                                          <span class="glyphicon glyphicon-minus"></span>
                                        </button>
                                    </span>
                                                                    <input type="number" id="quantity"
                                                                           class=" align-items-center qty-input"
                                                                           value="{{ item.product_quantity }}">
                                                                    <span class="input-group-btn">
                                        <button type="button" id="quantity-right-plus"
                                                class=" changeQuantity btn btn-primary btn-number"
                                                data-type="plus">
                                            <span class="glyphicon glyphicon-plus"></span>
                                        </button>
                                    </span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                {% else %}
                                                    <h3>Out of Stock</h3>
                                                {% endif %}
                                            {% endif %}

                                        </div>
                                        <div class="col-md-3 col-lg-2 col-xl-2 offset-lg-1">
                                            <h5 class="mb-0">$ {{ item.product.selling_price }}</h5>
                                        </div>
                                        <div class="col-md-1 col-lg-1 col-xl-1 text-center">
                                            <a href="#!" class="text-danger delete-cart-item">Remove</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}

and here jquery code:

$(document).ready(function () {

    var quantitiy = 0;
    $('#quantity-right-plus').click(function (e) {

        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        var quantity = parseInt($('#quantity').val());

        // If is not undefined

        $('#quantity').val(quantity + 1);


        // Increment

    });

    $('#quantity-left-minus').click(function (e) {
        console.log("jjjj")
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        var quantity = parseInt($('#quantity').val());

        // If is not undefined

        // Increment
        if (quantity > 0) {
            $('#quantity').val(quantity - 1);
        }
    });




//    change the quantity in the cart
     $('.changeQuantity').click(function (e) {
     e.preventDefault();
     var product_id = $(this).closest('.product_data').find('.prod_id').val()
     var product_qty = $(this).closest('.product_data').find('.qty-input').val()
     var token = $('input[name=csrfmiddlewaretoken]').val()

    $.ajax({
        method: 'POST',
        url: '/update_cart/',
        data: {
            'product_id' : product_id,
            'product_qty' : product_qty == null ? 1 : product_qty,
            csrfmiddlewaretoken: token

        },
        success: function(response) {
            console.log(response.status)
            alertify.success(response.status)
        }
    })
})



});

and here the python code

def update_cart(request):
    if request.method == 'POST':
        prod_id = int(request.POST.get('product_id'))
        if Cart.objects.filter(user=request.user, product_id=prod_id):
            prod_qty = int(request.POST.get('product_qty'))
            cart = Cart.objects.get(product_id=prod_id, user=request.user)
            cart.product_quantity = prod_qty
            cart.save()
            return JsonResponse({'status': "Updated Successfully"})
    return redirect('/')

Upvotes: 0

Views: 183

Answers (2)

seokmin-kang
seokmin-kang

Reputation: 209

Change right-button, left-button, input-quantity like this.

<button type="button" id="{{ item.product_id }}-right-plus" class="quantity-right-plus changeQuantity btn btn-primary btn-number" data-type="plus">

<button type="button" id="{{ item.product_id }}-left-minus" class="quantity-left-minus changeQuantity btn btn-primary btn-number" data-type="minus">

<input type="number" id="{{ item.product_id }}-quantity" class="align-items-center qty-input" value="{{ item.product_quantity }}">

and change the jQuery code.

$('.quantity-right-plus').click(function (e) {

    // Stop acting like a button
    e.preventDefault();

    // Get the element ID
    const elementId = $('this').attr('id').split('-')[0]

    // Get the field name
    const quantity = parseInt($(`#{elementId}-quantity`).val());

    // If is not undefined

    $(`#{elementId}-quantity`).val(quantity + 1);


    // Increment

});

$('.quantity-left-minus').click(function (e) {

    // Stop acting like a button
    e.preventDefault();

    // Get the element ID
    const elementId = $('this').attr('id').split('-')[0]

    // Get the field name
    const quantity = parseInt($(`#{elementId}-quantity`).val());

    // If is not undefined

    // Increment
    if (quantity > 0) {
        $(`#{elementId}-quantity`).val(quantity - 1);
    }
});

Upvotes: 1

cheryllium
cheryllium

Reputation: 574

It's because $('#quantity') only selects the last element on the page with the #quantity ID. And you have the same id='quantity' on the input element for every item's quantity. $('#quantity') will only select the last input element on the page because there should only be one element on the page per ID, so it's just going to grab the last one. Having multiple elements on the page with the same ID is an error, IDs are supposed to be unique.

There are several correct ways to do what you're looking to do. One option is to give each input a unique ID, for example, id='quantity-{{ item.product_id }}' instead, and add a data attribute to the increment/decrement buttons you can use to get the product ID in your jQuery so that it knows which input to update.

Upvotes: 1

Related Questions