I am displaying a list of users in a table. Then, I have a button to allow a user to view more details about a specific user. However, I am having a hard time getting the ID for the user that is clicked on. I am not sure why it's not working. What am I doing wrong? I tried several options, and none of them work.
Partial code of how data the links are generated in my view.
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">@item.UserID</div></td>
<td><div class="centerText">@item.FirstName</div></td>
<td><div class="centerText">@item.LastName</div></td>
<td><div class="centerText"><a href="#" class="btn btn-default Detail" id="@item.UserID">Details</a></div></td>
</tr>
}
}
}
My jQuery function
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).attr('id');
console.log('dt');
});
});
I also tried it this way:
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">@item.UserID</div></td>
<td><div class="centerText">@item.FirstName</div></td>
<td><div class="centerText">@item.LastName</div></td>
<td><div class="centerText"><a href="#" class="btn btn-default Detail" onclick="test(@item.UserID)" data-id="@item.UserID">Details</a></div></td>
</tr>
}
}
}
Here is the Javascript function that I created. It kept giving
function test(e){
console.log(e);
};
I get this error:
0x800a1391 - JavaScript runtime error: 'test' is undefined
updated on 11/21/15 @7:53 AM EST
I removed the for loop and created a single cell with 1 click button. The click event is not registered. I tried it with 'on', 'live', and 'delegate' with no success.
<div class="table table-responsive" style="width:100%;height:100%;">
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th><div class="centerText">Date Created</div></th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="6"><div class="centerText"><a href="#" class="btn btn-default Detail">Detail</a></div></td>
</tr>
</tbody>
</table>
</div>
@section Scripts {
<script type="text/javascript">
$('.table tbody tr td div').delegate('.Detail','click', function ()
{
console.log('you click me');
});
</script>
}
function test(e)instead ofvar function test(e).var dt = $(this).data('id');- your adding adata-attribute to the link, not an`idattribute$('.table').on('click', '.Detail', function() {