hemnath mouli
hemnath mouli

Reputation: 2755

Adding another row in a table using javascript

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

Answers (3)

Mark&#39;s Enemy
Mark&#39;s Enemy

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

Sid M
Sid M

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

Ole Spaarmann
Ole Spaarmann

Reputation: 16749

You forgot to add the id to your table. Also you cannot have different numbers of tds 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

Related Questions