Nupp
Nupp

Reputation: 13

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>

  }    
}

Upvotes: 1

Views: 386

Answers (1)

Jaimin Dave
Jaimin Dave

Reputation: 1222

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>

Upvotes: 1

Related Questions