Reputation: 517
I have this html (with Razor to display rows in table) :
@foreach (var item in Model.AllGroups)
{
<tr class="group-row" data-id="@item.Id">
<td class="align-middle text-primary">
<h4 class="group-name" > @Html.DisplayFor(m => item.Name)</h4>
</td>
<td>
<a class="btn btn-small btn-primary detail-group-btn">
<i class="fas fa-user text-white"></i>
</a>
<a class="btn btn-small btn-secondary edit-group-btn">
<i class="fa fa-edit text-primary"></i>
</a>
<a class="btn btn-small btn-danger delete-group-btn">
<i class="fa fa-trash text-white bg-"></i>
</a>
</td>
</tr>
}
I bind a click event on the delete-group-btn
button and when I click I want to retrieve the text value of <H4>
tag.
At this step I'm doing it like that :
$(this).closest('.group-row').find('.group-name').text()
I works but I'm not sure it is the right and optimized way.
Is there a better solution?
Upvotes: 0
Views: 46
Reputation: 1555
I'd add the id to a "data-target" attribute, something like this:
@foreach (var item in Model.AllGroups)
{
<tr class="group-row" data-id="@item.Id">
<td class="align-middle text-primary">
<h4 class="group-name" id="@item.Id"> @Html.DisplayFor(m => item.Name)</h4>
</td>
<td>
<a class="btn btn-small btn-primary detail-group-btn">
<i class="fas fa-user text-white"></i>
</a>
<a class="btn btn-small btn-secondary edit-group-btn">
<i class="fa fa-edit text-primary"></i>
</a>
<a class="btn btn-small btn-danger delete-group-btn" data-target="@item.Id">
<i class="fa fa-trash text-white bg-"></i>
</a>
</td>
</tr>
}
To be retrieved like this:
$( '#' + $(this).data('target') ).text();
Upvotes: 1
Reputation: 41
Since you probably have multiple rows (because of running foreach) you could assign a unique id to h4 element in each row.
For example id="h4_0" for h4 element in first row, id="ht_1" for h4 element in second row, ...
Then you can add "onclick" attribute to each button which calls certain function with row index as a parameter. In that function you combine row index with "h4_" and you have an id of h4 element in the same row.
Example for first row:
<h4 class="group-name" id="h4_0" > @Html.DisplayFor(m => item.Name)</h4>
<a class="btn btn-small btn-danger delete-group-btn" onclick="doSomething(0)">
<script>
function doSomething(rowIndex) {
var h4Id = "h4_" + rowIndex;
// Do something ...
}
</script>
This is not the best solution but it also works :)
Upvotes: 1