I have foreach
@foreach (var produkt in ViewBag.OnePageOfProducts){
<button id="submitButton" value="@produkt.ProductId">Add to Cart</button>
}
and call method jquery ajax
<script>
$(document).ready(function () {
var id
var quantity = 1;
$('#submitButton').click(
/*error dont work read value from button id */
var id = $('#submitButton').attr('value'); /*I dont know how to read difrent id for any product*/
function () {
$.ajax({
type: "POST",
url: '@Url.Action("AddToCart2", "Cart")',
data: { id: id, quantity: quantity },
success: function (result) {
$("#mydiv").load(location.href " #mydiv");
},
error: function (abc) {
alert(abc.statusText);
},
});
})
})
</script>
I dont know how to read diffrent #submitbutton for one to product becouse read only one first element.
var id = $('#submitButton').attr('value'); is only one but I have for example 20 elelements, have i can read difrent element id for @foreach (var produkt in ViewBag.OnePageOfProducts)
Any idea?
CodePudding user response:
As per freedomn-m's comment, your code will generate buttons with same ids, and ids should be unique. You can also directly assign function to it:
@foreach (var produkt in ViewBag.OnePageOfProducts) {
<button onclick='addToCart("@produkt.ProductId")'>Add to Cart</button>
}
And define the function:
function addToCart(productId) {
$.ajax({
type: "POST",
url: '@Url.Action("AddToCart2", "Cart")',
data: {
id: productId
quantity: 1
},
success: function(result) {
$("#mydiv").load(location.href " #mydiv");
},
error: function(abc) {
alert(abc.statusText);
},
});
})
CodePudding user response:
<script>
$(document).ready(function () {
// Initialization
var id;
var quantity = 1;
$('.submitButton').click(
function () {
var id = $(this).attr('value')
$.ajax({
type: "POST",
url: '@Url.Action("AddToCart2", "Cart")',
data: { id: id, quantity: quantity },
success: function (result) {
$("#mydiv").load(location.href " #mydiv");
},
error: function (abc) {
alert(abc.statusText);
},
});
})
})
</script>
Its work for me. Thx