0

I have a table like this link.

enter image description here

How can I know the td(input) I clicked is the first row or last row?

And how can I know the column index of td and the row index of td I clicked?

I know I can use $(this), but how to do?

$("#table_reach_condition_appoint tbody td").click(function(){
    //$(this)
})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Could this be your case? https://stackoverflow.com/questions/788225/table-row-and-column-number-in-jquery – bimbo1989 Aug 08 '18 at 15:32

3 Answers3

0
$("#table_reach_condition_appoint tbody td").each(function() {
  $(this).on('click', function() {
     var row = $(this).parent('tr').index(),
             column = $(this).index();
     console.log(row, column);
  });
})

Row and Column will start at 0 unless otherwise specified.

Gavin Thomas
  • 1,196
  • 6
  • 10
  • no need to wrap this in an `each`. Just adding redundant code since `$(selector).method()` runs internal `each` – charlietfl Aug 08 '18 at 14:39
0

Here is an example how you can do it. index() returns the index of the current position of the selected element. It starts with index 0. Therefore we need to add +1 to the result to get the correct row/column number.

$(function(){
  $('td').on('click', function(){
    var columnNumber = $(this).index() + 1; // add 1 because index starts with 0
    var rowNumber  = $(this).parent('tr').index() + 1;
    
    //Check if the culculated row number is 1
    firstcolumn = (columnNumber === 1);
    firstRow = (rowNumber === 1);
    
    //Compare the clicked element with the last element using jQuery's is() function.
    lastRow = $(this).parent('tr').is(':last-child');
    lastColumn = $(this).is(':last-child');
    
    console.log('clicked on: ' + $(this).text());
    console.log('row: ' + rowNumber);
    console.log('column: ' + columnNumber);
    
    if(firstcolumn) {
      console.log('firstColumn');
    }
    if(firstRow) {
      console.log('firstRow');
    }
    if(lastRow) {
      console.log('lastRow');
    }
    if(lastColumn) {
      console.log('lastColumn');
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1A</td>
    <td>2A</td>
    <td>3A</td>
    <td>4A</td>
  </tr>
  <tr>
    <td>1B</td>
    <td>2B</td>
    <td>3B</td>
    <td>4B</td>
  </tr>
</table>
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
0
$("#table_reach_condition_appoint tbody td").click(function(){
    var tbl_row_count = $('#table_reach_condition_appoint>tbody>tr').length;
    var col_no = parseInt($(this).index())+1;
    var row_no = parseInt($(this).closest('tr').index())+1;
    if(row_no == 1)
    {
      alert('first row');
    }
    if(row_no == tbl_row_count)
    {
      alert('last row');
    }
   alert('You clicked row no'+row_no+' col no'+col_no);    
});
arjun
  • 75
  • 9