There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery.
$('.tbody').on('click','tr td:nth-child(1)', function () {
var id = $(this).closest("td").find('td:eq(1)').text();
alert(id)
});
I have implemented an onclick function to extract the value of the second td based on the provided code. However, upon execution, I receive an empty alert. I am uncertain of what went wrong and require assistance.
According to my understanding, $(this).closest("td").find('td:eq(1)').text() should locate the next td and the .text()
method should display the content within that td. Is this correct?
The following snippet illustrates the issue described above
Your help will be greatly appreciated!
Thank you in advance!
$(function () {
$('.tbody').on('click','tr td:nth-child(1)', function () {
var id = $(this).closest("td").find('td:eq(1)').text();
alert(id)
});
});
#items {
border-collapse: collapse;
width: 100%;
}
#items th {
background-color: #009999;
color: white;
border : 1px solid;
}
#items td{
border : 1px solid;
}
#items tbody{
height:200px;
overflow-y:auto;
}
#items thead,.tbody{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; " id="items">
<thead>
<tr>
<th style="width:100px;">Fee Type</th>
<th style="width:100px;">Charges per Qty</th>
<th style="width:100px;">Qty</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td style="width:100px;">a</td>
<td style="width:100px;">b</td>
<td style="width:100px;">c</td>
</tr>
<tr>
<td style="width:100px;">d</td>
<td style="width:100px;">e</td>
<td style="width:100px;">f</td>
</tr>
</tbody>
</table>
</div>