Reputation: 2269
Here is my scenario:
I have a table that displays the Name, Age, and Details content on each row. When a user selects the Details
button, it should trigger a modal and show additional content specific to that Person in the table.
Issue at hand:
I am using Razor syntax
and dynamically generating the rows within the table.
Question: How can I get the row index value for that specific row when selecting the
Details
button
Additional Notes:
I did some research online, but couldn't find anything that helped me in my scenario.
Html
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var viewModel in Model)
{
<tr>
<td>@viewModel.Name</td>
<td>@viewModel.Age</td>
<td><button onclick="PersonViewModel(this)" type="button" class="btn btn-success" data-toggle="modal" data-target="#details-modal"><span class="fa fa-external-link-square"></span> Details</button></td>
</tr>
}
</tbody>
</table>
</div>
JavaScript:
function PersonViewModel(x) {
$('body').on('click', 'a.showMore', function(event) {
var rowIndex = $(this).closest('tr').index();
alert("Row index is: " + rowIndex);
});
}
Upvotes: 0
Views: 4100
Reputation: 381
Please check my code instead of your
function PersonViewModel(x) {
var index = $(".table tr").index( $(x).parents('tr'));
alert(index);
}
Upvotes: 0
Reputation: 487
You can try like this. I think this will help you.
$(this).parents('tr')).index()
This will give you parent tr and index() function will give index of that tr.
Upvotes: 1
Reputation: 133423
You are binding event in the PersonViewModel
click handler. In order to get the index of parent tr
, you need to use the x
object.
Use
function PersonViewModel(x) {
var rowIndex = $(x).closest('tr').index();
alert("Row index is: " + rowIndex);
}
Upvotes: 2