Reputation: 2755
I have created a table. I need to add a new row using javascript. Can anybody fix it.
<head>
<script>
var num=1;
function addrow(){
num++;
var x = document.getElementById("add");
x.innerHTML= x.innerHTML +"<tr><td>Content_"+num+"</td></tr>";
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table>
<tr><td>Content_1</td></tr>
//* I wanted to add a new row here *//
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>
I wanted to add a new row in between the rows!! Can anybody help? Thanks in advance!
Upvotes: 1
Views: 1401
Reputation: 89
var num=1;
function addrow(){
var table = document.getElementById("add");
var row = table.insertRow(num);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL"+num;
cell2.innerHTML = "NEW CELL"+num;
num++;
}
This would work :)
Upvotes: 1
Reputation: 4354
Do it like this
<head>
<script>
var num=1;
function addrow(){
var table = document.getElementById("add");
var row = table.insertRow(num);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL"+num;
cell2.innerHTML = "NEW CELL"+num;
num++;
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table id="add">
<tr><td colspan="2">Content_1</td></tr>
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>
Fiddle : Demo
Upvotes: 1
Reputation: 16749
You forgot to add the id
to your table. Also you cannot have different numbers of td
s per row. If you want one cell to take the space of two columns then add colspan="2"
<head>
<script>
var num=1;
function addrow(){
num++;
var x = document.getElementById("add");
x.innerHTML= x.innerHTML +"<tr><td>Content_"+num+"</td></tr>";
}
</script>
<title>Add new row with js</title>
</head>
<body>
<table id="add">
<tr><td colspan="2">Content_1</td></tr>
<tr><td>Content_End</td><td><button onclick="addrow()">+</button></td></tr>
</table>
</body>
Upvotes: 0