Syazri Aris
Syazri Aris

Reputation: 53

add multiple row dynamically

This is example of my code.. from the example, I've got two rows.. What I want to do is, I want to add the two rows dynamically.. thank you

<table id="datatable">
    <tr>
        <td><input type="text" /></td>
    </tr>
    <tr>
        <td><input type="text" /></td>
    </tr>
</table> 
<button type="button" id="add" onclick="addRow('dataTable')">
    <b>Add</b>
</button>
function addRow(tableID) {
    alert('ttt');
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
    for (var i = 0; i < colCount; i++) {
        var newcell = row.insertCell(i);
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
        //alert(newcell.childNodes);
        switch(newcell.childNodes[0].type) {
            case "text":
                newcell.childNodes[0].value = "";
                break;
            case "checkbox":
                newcell.childNodes[0].checked = false;
                break;
            case "select-one":
                newcell.childNodes[0].selectedIndex = 0;
                break;
        }
    }
}

jsfiddle example

Upvotes: 1

Views: 2727

Answers (3)

William Buttlicker
William Buttlicker

Reputation: 6000

Try this:

HTML

<table id="datatable">
       <tr>
        <td><input type="text"  /></td>
       </tr>
       <tr>
        <td><input type="text"  /></td>
       </tr>
     </table> 

<button type="button" id="add" onclick="addRow('dataTable')">
        <b>Add</b>
 </button>

JS

 $(document).ready(function() {
    $('#add').click(function(){ 
        $('#datatable').append(' <tr> <td>Account No</td> <td>:</td> <td colspan="2"><input size="20" type="text" /></td> <td>Bill No</td> <td>:</td> <td><input type="text" /></td> </tr> <tr> <td>Name</td> <td>:</td> <td colspan="2"><input type="text" /></td> <td>Bill date</td> <td>:</td> <td><input type="text" /></td> </tr>');
}); 
});

Fiddle: http://jsfiddle.net/zLXmQ/4/

Upvotes: 2

ebram khalil
ebram khalil

Reputation: 8321

simply you can do this :

function addRow(tableId)
{
  $('#' + tableId + ' tr:last').after('<tr><td>Enter You New Row Data Here..</td></tr>');
}

for more information check this : Add table row in jQuery

Upvotes: 0

Four_lo
Four_lo

Reputation: 1150

Just browsing through and would like to point out that your table id- is datatable and your parameter is dataTable. hopefully thats pertinent

Upvotes: 0

Related Questions