I have html elements in foreach
. I cannot declare ID name to those manually.
I used id='ProductSelect_@(item.Id)'
to set Id:
foreach (var item in Model)
{
<a href="#" id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
But, now I need .click() function for eash <a>
link to do my some operations. How write click function for dynamic ID's?
I checked this, but it does not work :
$("#ProductSelect_@(item.Id)").click(function () {
//any operation
});
Edit:
<script>
$(document).ready(function () {
$('.select-link').click(function() {
var id = $(this).attr('data-id');
url = '@Url.Action("SelectThis", "Product")';
var data = { id: '@Model.Id' };
$.post(url, data, function (result) {
if (result.success) {
alert("Thanks");
}
else {
alert("Problem occured...");
}
});
});
});
</script>
This click() functions send request to controller iteration counts times. What is wrong in my code?
I would suggest using attributes.
foreach (var item in Model)
{
<a href="#" data-id='@item.Id' id='ProductSelect_@(item.Id)' class="select-link">Select this</a>
}
then in JS...
$('.select-link').click(function()
{
var id = $(this).attr('data-id');
});
That way you're wired to all similar links (e.g. select-list
) without a separate handler function for each #id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With