Nupp Nupp - 10 days ago 5
jQuery Question

JQuery: Read selected razor(@item.Id) from foreach.

I list all products via foreach. I'm trying to show my selected

product.Id
via Alert by clicking on the button that were created from foreach. But I don't know how to proceed. How do I allow alert to read the specific
item.ID
that were selected/clicked?

<script type="text/javascript">

$(document).ready(function () {
$('.add-to-cart').click(function () {
alert(item.ID); //something like this
});
});

</script>


-

@foreach (var item in Model) {

/*@item.ID*/

<button class="add-to-cart">Add to Cart</button>

}
}

Answer

You can use onclick() function like this:

   <button class="add-to-cart" onclick = "AddToCart('@item.Id')">Add to Cart</button>

in your script,

<script>
    function AddToCart(id)
    {
          alert(id);
    }
    </script>

OR

you can use data-* attribute to button,

<button class="add-to-cart" data-ID="@item.ID">Add to Cart</button>

in your script,

 <script>
    $(document).ready(function () {
            $('.add-to-cart').click(function () {
              alert($(this).data('ID'));    
            });
        });
 </script>
Comments