0

Does anyone know how to make the button Add Rows work? I want to make if I click that button then rows can be added and the number increased automatically. I've tried, but it doesn't work. Please help. Thank you.

function addRow() {
  var x = document.getElementById('Table');
  var new_row = x.rows[1].cloneNode(true);
  var len = x.rows.length;
  new_row.cells[0].innerHTML = len;

  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
  inp1.id += len;
  inp1.value = '';
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
  inp2.id += len;
  inp2.value = '';
  x.appendChild(new_row);

}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Document</title>
</head>

<body>
  <input type="button" value="Add Row" onclick="addRow()" />
  <table id="Table" border="1" cellpadding="10" cellspacing="0">
    <tr>
      <th>NO</th>
      <th>DESCRIPTION</th>
      <th>ACTION</th>
    </tr>
    <tr>
      <th>1</th>
      <th> </th>
      <th> </th>
    </tr>
    <tr>
      <th>2</th>
      <th> </th>
      <th> </th>
    </tr>
    <tr>
      <th>3</th>
      <th> </th>
      <th> </th>
    </tr>
  </table>
</body>

</html>

2
  • where's the input within the rows? Commented Dec 25, 2020 at 12:57
  • Please also re-format your question properly and add the code here instead of images Commented Dec 25, 2020 at 12:58

1 Answer 1

1

Use something like this to achieve the results:

function addRow() {
    var x = document.getElementById('Table');
    var rows = document.querySelectorAll('Table tr').length;
    var new_row = '<tr><th>'+rows+'</th><th> </th><th> </th></tr>';
    x.insertAdjacentHTML('beforeend',new_row);
 }
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Document</title>
  </head>
  <body>
    <input type="button" value="Add Row" onclick="addRow()"/>
    <table id="Table" border = "1" cellpadding="10" cellspacing="0">
      <tr>
        <th>NO</th>
        <th>DESCRIPTION</th>
        <th>ACTION</th>
      </tr>
      <tr>
        <th>1</th>
        <th> </th>
        <th> </th>
      </tr>
      <tr>
        <th>2</th>
        <th> </th>
        <th> </th>
      </tr>
      <tr>
        <th>3</th>
        <th> </th>
        <th> </th>
      </tr>
    </table>
  </body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.