Advertisements
I want to get the value of a table cell by click a button in the same row of this cell. this cell is in the previous column of the button’s column, this is my trying code:
<table class="table table-bordered table-hover" >
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.CategoryId)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
<div class="btn-group-sm">
<button class="btn btn-primary" onclick="addArticle(this)">Add</button>
<button class="btn btn-warning">Edit</button>
</div>
</td>
</tr>
}
</tbody>
</table>
JS:
function addArticle(btn) {
var RowNumber = btn.previousSibling.innerHTML;
alert(RowNumber);
}
This code is not working,it displays undefined. Any help?
>Solution :
You need to walk the DOM tree:
- btn parent
- div parent
- table cell previous sibling
function addArticle(btn) {
var RowNumber = btn.parentElement.parentElement.previousElementSibling.innerHTML;
alert(RowNumber);
}