Reputation: 4666
I have a form being generated using a for loop.
{% for id in data %}
<form id="add_to_cart_{{id}}" method="POST" action="{% url 'add_to_cart' %}">
{{id}}
<button type="submit" id="product_id_{{id}}" value="{{id}}">Add to cart</button>
</form>
{% endfor %}
This generates a list of buttons on html page, each having a different value according to the {{id}}
. Now I want to post an ajax call to my django view and pass the corresponding value according to button.
The problem is my ajax call only takes value for the first element. So how to dynamically pass the value of button to ajax call?
My ajax function when there is a static form:
jQuery(document).ready(function($){
$('#add_to_cart').on('submit', function(event){
event.preventDefault();
$.ajax({
url : "/add_to_cart/", // the endpoint
type : "POST",
cache: false,
async: "true",
data : { product_id : $('#product_id').val()},
success : function(json) {
console.log("success");
alert("Product Added To Cart.");
},
error : function(xhr,errmsg,err) {
console.log(err);
console.log(errmsg);
}
});
});
});
Upvotes: 1
Views: 55
Reputation: 4666
For dynamically generated form you have to have different ids for each form as in question. id="form_id_{{id}}"
. Then add a class to the form as the class can be same for multiple elements.
Like:
<form id="add_to_cart_{{id}}" class="AddToCartClass" action= ...
Then in jQuery access the event with the class name. Like:
jQuery(document).ready(function($){
$(document).on('submit', '.AddToCartClass', function(event){
event.preventDefault();
var prod_id = $(this).closest('form').find('#product_id').val();
This way you can access data for a form generated by for loop.
Upvotes: 1
Reputation: 7207
$(this)
should have the button you clicked. So maybe $(this).val()
instead of $('#product_id').val()
.
Upvotes: 0