Search code examples
javascripthtmlrow

Html table text entry placeholder as row index


I have a html table in which I can dynamically add and remove rows. To avoid confusion further on, I would like the placeholder of the first entry of each row to be the index of said row.

A small working example:

<!DOCTYPE html>
<html>
<body> 

<script src="https://code.jquery.com/jquery-1.12.1.js"   integrity="sha256-VuhDpmsr9xiKwvTIHfYWCIQ84US9WqZsLfR4P7qF6O8="   crossorigin="anonymous"></script>
<script>
 window.SomeDeleteRowFunction = function SomeDeleteRowFunction(o) {
  var p=o.parentNode.parentNode;
  p.parentNode.removeChild(p);
 }

 $('document').ready(function() {
  $('.add_another').click(function() {
   $("#tbl").append('<tr><td><input type="text" class="txtbox" value="" placeholder=x.rowIndex/>  </td></tr>');
  });
 })</script>

<table id="tbl">
<tr>

</tr>
<tr>
<td><input type="text" name="links"  placeholder=x.rowIndex /></td>
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"/></td>          
</tr>
</table>
<input type="submit" class="button add_another" value="Add another line"/>

</body>
</html> 

In this example I would like the x.rowindex to be replaced with the current row index.

Is there a way to do this?

Thank you!


Solution

  • window.SomeDeleteRowFunction = function SomeDeleteRowFunction(o) {
      var p = o.parentNode.parentNode;
      p.parentNode.removeChild(p);
    
      $('#tbl tr').each(function(i) {
        $(this).find('input').eq(0).attr("placeholder", i+1);
      });
    }
    
    $('document').ready(function() {
      $('.add_another').click(function() {
        $("#tbl").append('<tr><td><input type="text" class="txtbox" value="" placeholder="' + ($('#tbl tr').length + 1) + '"/></td><td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)" /></td></tr>');
      });
    
    });
    <!DOCTYPE html>
    <html>
    
    <body>
    
      <script src="https://code.jquery.com/jquery-1.12.1.js" integrity="sha256-VuhDpmsr9xiKwvTIHfYWCIQ84US9WqZsLfR4P7qF6O8=" crossorigin="anonymous"></script>
      <table id="tbl">
        <tr>
          <td><input type="text" name="links" placeholder=1 /></td>
          <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)" /></td>
        </tr>
      </table>
      <input type="submit" class="button add_another" value="Add another line" />
    
    </body>
    
    </html>