Проблема с обновлением счетчика с помощью jquery внутри цикла с django
все работает правильно, за исключением того, что при нажатии на кнопки увеличения или уменьшения, обновляется только последний продукт в корзине!!!, для других корзин, я могу обновить значение вручную и нажать кнопку, она будет обновлена без проблем!!!
это код для .html в django
и вот код jquery:
$(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)
}
})
})
});
и здесь код python
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('/')
Потому что $('#quantity') выбирает только последний элемент на странице с идентификатором #quantity. И у вас есть такой же id='quantity' на элементе ввода для каждого количества товара. $('#quantity') выберет только последний элемент ввода на странице, потому что на странице должен быть только один элемент на ID, поэтому он просто возьмет последний. Наличие нескольких элементов на странице с одинаковым ID является ошибкой, ID должны быть уникальными.
Существует несколько правильных способов сделать то, что вы хотите сделать. Один из вариантов - присвоить каждому входу уникальный ID, например, id='quantity-{{ item.product_id }}', и добавить атрибут data к кнопкам увеличения/уменьшения, который можно использовать для получения ID продукта в jQuery, чтобы он знал, какой вход обновлять.
Измените правую кнопку, левую кнопку, input-quantity следующим образом.
<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 }}">
и измените код jQuery.
$('.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);
}
});