1

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!

1
  • the above code is looking for the element with id 'add' that does not exists. insert the id 'add' in the html. Commented Jun 23, 2015 at 14:54

3 Answers 3

1

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

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

Comments

1
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 :)

1 Comment

Hey welcome to stack, Here only code answer are not well received, If would be great if you can explain your answer also so that others having same problem in future might be benefited,
0

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>

2 Comments

This will add rows in end not in between
I need output such as <tr><td>Content_1</td></tr> <tr><td>Content_3</td></tr> <tr><td>Content_2</td></tr> <tr><td>Content_End</td></tr>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.