如何将按钮和字段值与 jQuery 连接 for 对象从模板循环



当我发布表单时,任何数量都会使用第一个数量字段中的值进行更新。我不知道如何连接数量值和此值的特定提交按钮。

我在模板中的表单.html

{% for item in cart %}
    <form action="{% url 'product_update' item.product.id %}" method="POST">
      {% csrf_token %}
      <input type="number" class="form-control" id='quantity' value="{{ item.quantity }}">
      <button type="submit" class="btn btn-link update-product">
          <span class="glyphicon glyphicon-refresh"> </span>
      </button>
    </form>
{% endif %}

的观点(我使用django-cart作为我的购物车)

def product_update(request, id):
    product = Product.objects.get(id=id)
    cart = Cart(request)
    quantity = request.POST['quantity']
    unit_price = product.price
    cart.update(product, quantity, unit_price)
    return JsonResponse({'status': 'success'})

我的脚本

function updateProductQuantity(){
  $('button.update-product').click(function(){
    var link = $(this).parents('form')
    var quantity = $('#quantity').val()  //I think my problem is here
    $.ajax({
        'url': link.attr('action'),
        'type': 'POST',
        'dataType': 'json',
        'data': {
            'quantity': quantity,
            'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
        },
        'success': function(data, status, xhr){
            alert(data['status']);
            return false;
        }
    });
    return false;
});
}

你可以做:

 var quantity = $(this).parents('form').find('#quantity').val();

或者更有效地选择表单本身。前任:

 $('form').on('submit', function(){
    var link = $(this);
    var quantity = $(this).find('#quantity').val();
    $.ajax({
        'url': link.attr('action'),
        'type': 'POST',
        'dataType': 'json',
        'data': {
            'quantity': quantity,
            'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
        },
        'success': function(data, status, xhr){
            alert(data['status']);
            return false;
        }
    });
    return false;
});

您的问题是您说"选择页面上的第一个"#quantity"并获取其值。要获取目标表单的位置 #quantity 值。

最新更新