title: Get row index of a table javascript
body: <p>I know this question has been asked many times, I went through most of the suggestions and none of the solutions seem to be working for me.</p>
  
  <p>I have a table in a modal in which I am allowing the user to make some changes. I then use these values to update the data in the database. </p>
  
  <p>My table rows are created by echoing the HTML code</p>
  
  <pre><code>echo "&lt;tr&gt; ";                   
  echo "&lt;td &gt; $row_counter  &lt;/td&gt;";
  echo "&lt;td style='width:200px' class='left_align' &gt; $lstr_product_name &lt;/td&gt;";
  echo "&lt;td  &gt; $lstr_department_name &lt;/td&gt;";
  echo "&lt;td  &gt; &lt;input type='text' name='unit_cost' class='form-control unit_cost' style='width:50px;' value='$lint_unit_cost' /&gt; &lt;input name='product_id' data-id='$lint_product_id' class='form-control product_id' value='$lint_product_id' type='hidden'/&gt; &lt;/td&gt;";
  echo "&lt;td  &gt; $lint_quantity_counted &lt;/td&gt;";
  echo "&lt;td  &gt; $lint_total_cost &lt;/td&gt;";
  </code></pre>
  
  <p>To update the proper values in the database I need to get the product_id name which I know that I can get by </p>
  
  <pre><code>var x = document.getElementsByName("product_id")[0].value;
  </code></pre>
  
  <p>However I need to get the correct row index to be able to POST the correct product_id. </p>
  
  <p>I have tried the following:</p>
  
  <pre><code>alert($(this).index()); 
  </code></pre>
  
  <p>But this always returns 0. The closest I got to a solution was by using </p>
  
  <pre><code>var rowID = $(this).closest('tr').index();
  alert(rowID);
  </code></pre>
  
  <p>The problem with this is that my editable cell is "unit_cost" which is the 4th cell in the tr. This means that the closest tr is not the one that the row that the cell is in but the one below. </p>
  
  <p>I have then tried </p>
  
  <pre><code>alert( "Row id: " + $("#tbl_store_product_sizes tr").this.rowIndex );
  </code></pre>
  
  <p>But also no luck. I have ran out of ideas, what is the proper way of doing this?</p>
  
  <p><strong>EDIT</strong>
  All my javascript code is enclosed in the $(document).ready(function() 
  I am watching for the change of the unit_cost field using the following code</p>
  
  <pre><code>$(document.body).off( "change", ".unit_cost");
  $(document.body).on('change', '.unit_cost', function(event) 
  {
  
      var rowID = $(this).closest('tr').index();
      alert(rowID);
      var product_id = document.getElementsByName("product_id")[rowID].value;
      alert('The product id is: ' + x);
      var unit_cost = document.getElementsByName("unit_cost")[rowID].value;
  
  
  });
  </code></pre>