javabee
javabee

Reputation: 85

inserting row in the middle of a html table using javascript

I have a table which contains two rows.

<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>

I need to insert few rows between row1 and row2 using java script. I can achieve this by using java script create element. But I wish to add new rows using string html content. for example :

"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);

is there way like this to add rows in between?

Upvotes: 2

Views: 4806

Answers (3)

Deepan Raj
Deepan Raj

Reputation: 314

var button = document.getElementById('insert');

var table = document.getElementById('table');

button.onclick = function() {

var position=Math.round(table.rows.length / 2);

var row = table.insertRow(position);

row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
} 

 **after that if u can use like that u can increment ur row id also:**


 var rowId = '#' + tableId + ' tr';
    var k = 0;
    $(rowId).each(function () {
        var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
        if (ObjInput != null) {
            for (var j = 0; j < ObjInput.length; j++) {
                var inputId = $(ObjInput[j]).attr('id');
                inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
                $(ObjInput[j]).attr('id', inputId);
                $(ObjInput[j]).attr('name', inputId);
            }
            k++;
        }
    });

Upvotes: 0

ndugger
ndugger

Reputation: 7531

var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";

var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);

Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Upvotes: 8

schnawel007
schnawel007

Reputation: 4020

Use jQuery. There is a Function insertAfter();

$("#row1").insertAfter("your html");

http://jquery.com/

Upvotes: 3

Related Questions