Abdullah Mamun-Ur- Rashid Abdullah Mamun-Ur- Rashid - 6 months ago 216
Javascript Question

how to find cell text by row index by jquery

I have two rows of an html table:

<table id="mytable">
<tbody>
<tr><td rowspan="2">Row text</td><td>first cell</td><td>second cell</td><td>third cell</td></tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
</tbody>
</table>


I have to get the text of respective cell from first row while click on any input field of second row. As for example, if any user clicks on first input field of second row, 'first cell' should be get by jquery. I am trying to achieve this as below:

$('#mytable tbody tr td input[type="text"]').click( function(){
var thisRow = $(this).closest('tr').index();
var thisCell = $(this).closest('td').index();
var upRow = thisRow-1;
var firstCellText = upRow.find('td:eq(thiscell+1)').text();
alert(firstCellText);
});


but the text is not getting as expected. How to get the text?

Answer

You need to concatenate the string using +. Also you can select previous tr using prev(), no need to select it using index.

$('#mytable tbody tr td input[type="text"]').click(function() {
  var thisRow = $(this).closest('tr');
  var thisCell = $(this).closest('td').index();
  var firstCellText = thisRow.prev().find('td:eq(' + (thisCell + 1) + ')').text();
  alert(firstCellText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr>
      <td rowspan="2">Row text</td>
      <td>first cell</td>
      <td>second cell</td>
      <td>third cell</td>
    </tr>
    <tr>
      <td>
        <input type="text" value="" />
      </td>
      <td>
        <input type="text" value="" />
      </td>
      <td>
        <input type="text" value="" />
      </td>
    </tr>
  </tbody>
</table>

UPDATE : If you want to get text from first row always then use, :first to get first row. ( Suggested by @arunbahal )

var $row = $('#mytable tbody tr:first');
$('#mytable tbody tr td input[type="text"]').click(function() {
  var firstCellText = $row.find('td:eq(' + ($(this).closest('td').index() + 1) + ')').text();
  alert(firstCellText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr>
      <td rowspan="2">Row text</td>
      <td>first cell</td>
      <td>second cell</td>
      <td>third cell</td>
    </tr>
    <tr>
      <td>
        <input type="text" value="" />
      </td>
      <td>
        <input type="text" value="" />
      </td>
      <td>
        <input type="text" value="" />
      </td>
    </tr>
  </tbody>
</table>

Comments