Valkyriee Valkyriee - 8 days ago 7
jQuery Question

How to get value of a table cell when selected using jQuery

I have the following table, I need to get text value of cell next to selected cell, basically if

2
is clicked it needs to show me the value of cell next to it which is
eric
and so on. The table below is an example data is filled dynamically and I don't think I can give an ID to specific
<td>
.



$('#inputTable').on('click', 'tbody tr', function (e) {
e.preventDefault();
var rowIndex = $(this).find('span').text();
alert(rowIndex);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<table class="ui compact celled definition table" id="inputTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><span>Mike</span></td>
</tr>
<tr>
<td>2</td>
<td><span>eric</span></td>
</tr>
<tr>
<td>3</td>
<td><span>jonas</span></td>
</tr>
</tbody>
</table>





Since I didn't know how to find cell next to the clicked area I used
<span>
to find the text's value.

Answer

You need to use a more specific selector (for example body tbody td:first-child). This will select the first <td> element in each <tr>, and using siblings() we can select the next element in the row.

The following will work:

$('#inputTable').on('click', 'tbody tr td:first-child', function(e) {  
    var text = $(this).siblings('td').find('span').text();
    alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="ui compact celled definition table" id="inputTable">
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><span>Mike</span></td>
    </tr>
    <tr>
      <td>2</td>
      <td><span>eric</span></td>
    </tr>
    <tr>
      <td>3</td>
      <td><span>jonas</span></td>
    </tr>
  </tbody>
</table>

Notice that you also need to close your <span> elements, i.e.: <span>jonas</span>

Comments