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?
2
Answers
Its work for me. Thx
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:
And define the function: