Reputation: 27
I want to check if a row that has td with specific title and year. Here is my function and the problem is the title2 and year2 are set to undefined. How do I get cell values correctly?
var table = $("#mainTable");
var exist;
$(table).find("tr").each(function () {
var title2 = $(this).find("td:nth-child(1)").html();
var year2 = $(this).find("td:nth-child(2)").html();
if (title == title2 && year == year2)
exist = true;
});
return exist;
and my table:
<div class="table-responsive">
<table class="table table-condensed table-bordered table-striped table-hover" id="mainTable">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Emri</th>
<th scope="col">Viti</th>
</tr>
</thead>
<tbody>
@foreach (var subject in Model.Subjects)
{
<tr>
<td id="subjectId">@subject.Id</td>
<td id="subjectTitle">@subject.Title</td>
<td id="subjectYear"> @subject.Year</td>
<td>
<a id="add" class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
<a id="edit" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
<a id="delete" class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
}
</tbody>
</table>
</div>
Upvotes: 1
Views: 4812
Reputation: 5294
just a suggestion since it appears you are already creating your table using razor why not add data attributes of title and year to each row. then you can just use a selector.
$(`tr[data-title='three'][data-year='2017']`).css('background-color', 'green');
here is a fiddle demonstrating ( I used javascript instead of razor to create the table but you get the idea)
https://jsfiddle.net/xtqnksj4/
Upvotes: 2
Reputation: 171669
Probably due to including <thead>
row in your loop which has no <td>
Also nth-child
is not zero based so you are looking in wrong cells
Try searching only the <tbody>
rows by changing to
var table = $("#mainTable");
var exist;
table.find("tbody tr").each(function () {
var title2 = $(this).find("td:eq(1)").html();
var year2 = $(this).find("td:eq(2)").html();
if (title == title2 && year == year2)
exist = true;
// break the loop once found
return false;
});
return exist;
Finally, element id's are unique by definition. Use common classes instead
Upvotes: 3