Reputation: 1
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>
Upvotes: 0
Views: 206
Reputation: 2584
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>
Upvotes: 1