Home > Mobile >  problem with updating counter with jquery inside loop with django
problem with updating counter with jquery inside loop with django

Time:05-05

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 >
                                <div >
                                    <div >
                                        <div >
                                            <img
                                                    src="{{ item.product.product_image.url }}"
                                                     alt="Cotton T-shirt">
                                        </div>
                                        <div >
                                            <p >{{ item.product.name }}</p>
                                            <p><span >
                    {% if item.product.is_service %}
                        Service
                    {% else %}
                        Product
                    {% endif %}
                </span> <span >
                                        </div>
                                        <div >
                                            <input type="hidden" value="{{ item.product_id }}" >
                                            {% csrf_token %}
                                            {% if item.product.is_service == False %}
                                                {% if item.product.quantity >= item.product_quantity %}

                                                    <div >
                                                        <div >
                                                            <div >
                                                                <div >
                                    <span >
                                        <button type="button" id="quantity-left-minus"
                                                
                                                data-type="minus">
                                          <span ></span>
                                        </button>
                                    </span>
                                                                    <input type="number" id="quantity"
                                                                           
                                                                           value="{{ item.product_quantity }}">
                                                                    <span >
                                        <button type="button" id="quantity-right-plus"
                                                
                                                data-type="plus">
                                            <span ></span>
                                        </button>
                                    </span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                {% else %}
                                                    <h3>Out of Stock</h3>
                                                {% endif %}
                                            {% endif %}

                                        </div>
                                        <div >
                                            <h5 >$ {{ item.product.selling_price }}</h5>
                                        </div>
                                        <div >
                                            <a href="#!" >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('/')

CodePudding user response:

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

<button type="button" id="{{ item.product_id }}-right-plus"  data-type="plus">

<button type="button" id="{{ item.product_id }}-left-minus"  data-type="minus">

<input type="number" id="{{ item.product_id }}-quantity"  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);
    }
});

CodePudding user response:

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.

  • Related