2650

I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
  • 4
    Thxs Ash. I too am just learning jQuery and finding it hard to figure out the best way, especially simple things. The reason they are as 2 questions is because I posted one and then almost an hour later I realized I should have put the other one in and didn't think I should change the first. – Darryl Hein Oct 06 '08 at 05:53
  • 33
    Because of this: http://www.google.com/search?q=jquery+add+table+row – Darryl Hein Oct 05 '09 at 22:54
  • 19
    FYI - Avoid using multiple appends (slows down performance tremendously), rather build up your string or use JavaScript join which is much faster. – Gerrit Brink Apr 16 '10 at 09:32
  • 1
    see: https://stackoverflow.com/a/50365764/7186739 – Billu May 16 '18 at 08:24
  • 2
    Just in case if row is too complex, what I do is, keep first row hidden with required structure, make a clone and modify text and insert after first row, this way if you fetch data from ajax response your table will be created, remember clone it outside the loop, then use it to modify content inside loop. $("#mainTable tbody").append(row); row is the modified clone copy :) – Aadam May 16 '18 at 12:00

42 Answers42

2306

The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

You would end up with the following:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

I would therefore recommend this approach instead:

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');
Community
  • 1
  • 1
Luke Bennett
  • 32,786
  • 3
  • 30
  • 57
842

jQuery has a built-in facility to manipulate DOM elements on the fly.

You can add anything to your table like this:

$("#tableID").find('tbody')
    .append($('<tr>')
        .append($('<td>')
            .append($('<img>')
                .attr('src', 'img.png')
                .text('Image cell')
            )
        )
    );

The $('<some-tag>') thing in jQuery is a tag object that can have several attr attributes that can be set and get, as well as text, which represents the text between the tag here: <tag>text</tag>.

This is some pretty weird indenting, but it's easier for you to see what's going on in this example.

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
Neil
  • 24,551
  • 15
  • 60
  • 81
336

So things have changed ever since @Luke Bennett answered this question. Here is an update.

jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a <tr> and inserts it into the first <tbody> in your table or wraps it into a new <tbody> if one doesn't exist.

So yes your example code is acceptable and will work fine with jQuery 1.4+. ;)

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
Community
  • 1
  • 1
Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
185

What if you had a <tbody> and a <tfoot>?

Such as:

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>

Then it would insert your new row in the footer - not to the body.

Hence the best solution is to include a <tbody> tag and use .append, rather than .after.

$("#myTable > tbody").append("<tr><td>row content</td></tr>");
Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
ChadT
  • 7,598
  • 2
  • 40
  • 57
84

I know you have asked for a jQuery method. I looked a lot and find that we can do it in a better way than using JavaScript directly by the following function.

tableObject.insertRow(index)

index is an integer that specifies the position of the row to insert (starts at 0). The value of -1 can also be used; which result in that the new row will be inserted at the last position.

This parameter is required in Firefox and Opera, but it is optional in Internet Explorer, Chrome and Safari.

If this parameter is omitted, insertRow() inserts a new row at the last position in Internet Explorer and at the first position in Chrome and Safari.

It will work for every acceptable structure of HTML table.

The following example will insert a row in last (-1 is used as index):

<html>
    <head>
        <script type="text/javascript">
        function displayResult()
        {
            document.getElementById("myTable").insertRow(-1).innerHTML = '<td>1</td><td>2</td>';
        }
        </script>
    </head>

    <body>       
        <table id="myTable" border="1">
            <tr>
                <td>cell 1</td>
                <td>cell 2</td>
            </tr>
            <tr>
                <td>cell 3</td>
                <td>cell 4</td>
            </tr>
        </table>
        <br />
        <button type="button" onclick="displayResult()">Insert new row</button>            
    </body>
</html>

I hope it helps.

AminM
  • 1,658
  • 4
  • 32
  • 48
shashwat
  • 7,851
  • 9
  • 57
  • 90
40

I recommend

$('#myTable > tbody:first').append('<tr>...</tr><tr>...</tr>'); 

as opposed to

$('#myTable > tbody:last').append('<tr>...</tr><tr>...</tr>'); 

The first and last keywords work on the first or last tag to be started, not closed. Therefore, this plays nicer with nested tables, if you don't want the nested table to be changed, but instead add to the overall table. At least, this is what I found.

<table id=myTable>
  <tbody id=first>
    <tr><td>
      <table id=myNestedTable>
        <tbody id=last>
        </tbody>
      </table>
    </td></tr>
  </tbody>
</table>
pimvdb
  • 151,816
  • 78
  • 307
  • 352
Curtor
  • 737
  • 2
  • 9
  • 17
39

In my opinion the fastest and clear way is

//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');

//Then if no tbody just select your table 
var table = tbody.length ? tbody : $('#myTable');

//Add row
table.append('<tr><td>hello></td></tr>');

here is demo Fiddle

Also I can recommend a small function to make more html changes

//Compose template string
String.prototype.compose = (function (){
var re = /\{{(.+?)\}}/g;
return function (o){
        return this.replace(re, function (_, k){
            return typeof o[k] != 'undefined' ? o[k] : '';
        });
    }
}());

If you use my string composer you can do this like

var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = '<tr>'+
    '<td>{{id}}</td>'+
    '<td>{{name}}</td>'+
    '<td>{{phone}}</td>'+
'</tr>';


//Add row
table.append(row.compose({
    'id': 3,
    'name': 'Lee',
    'phone': '123 456 789'
}));

Here is demo Fiddle

Community
  • 1
  • 1
sulest
  • 1,006
  • 1
  • 10
  • 17
28

This can be done easily using the "last()" function of jQuery.

$("#tableId").last().append("<tr><td>New row</td></tr>");
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
Nischal
  • 958
  • 2
  • 10
  • 14
  • 9
    Good idea, but I think you'd want to change the selector to #tableId tr as right now you'd get the table add the row below the table. – Darryl Hein Jan 26 '10 at 17:13
24

I solved it this way.

Using jquery

$('#tab').append($('<tr>')
    .append($('<td>').append("text1"))
    .append($('<td>').append("text2"))
    .append($('<td>').append("text3"))
    .append($('<td>').append("text4"))
  )

Snippet

$('#tab').append($('<tr>')
  .append($('<td>').append("text1"))
  .append($('<td>').append("text2"))
  .append($('<td>').append("text3"))
  .append($('<td>').append("text4"))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="tab">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
    <th>City</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
    <td>New York</td>
  </tr>
</table>
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • I can successfully add dynamic data in a new row now but after using this method, my custom filter is not working ..Do you have any solution for that?T hank you – Arjun Jan 25 '19 at 05:28
  • I think you need to call an update function of some sort. Hade to tell without an example. – Anton vBR Jan 25 '19 at 06:22
19

I'm using this way when there is not any row in the table, as well as, each row is quite complicated.

style.css:

...
#templateRow {
  display:none;
}
...

xxx.html

...
<tr id="templateRow"> ... </tr>
...

$("#templateRow").clone().removeAttr("id").appendTo( $("#templateRow").parent() );

...
Dominic
  • 191
  • 1
  • 2
  • Thank you. This is very elegant solution. I like how it keeps the template within the grid. It make the code so much simpler and easier to read and maintain. Thanks Again. – Rodney Hickman Dec 26 '15 at 21:33
15

For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):

function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}

Usage example:

add_new_row('#myTable','<tr><td>my new row</td></tr>');
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Oshua
  • 151
  • 1
  • 2
13

I was having some related issues, trying to insert a table row after the clicked row. All is fine except the .after() call does not work for the last row.

$('#traffic tbody').find('tr.trafficBody).filter(':nth-child(' + (column + 1) + ')').after(insertedhtml);

I landed up with a very untidy solution:

create the table as follows (id for each row):

<tr id="row1"> ... </tr>
<tr id="row2"> ... </tr>
<tr id="row3"> ... </tr>

etc ...

and then :

$('#traffic tbody').find('tr.trafficBody' + idx).after(html);
Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
Avron Olshewsky
  • 131
  • 1
  • 2
12
    // Create a row and append to table
    var row = $('<tr />', {})
        .appendTo("#table_id");

    // Add columns to the row. <td> properties can be given in the JSON
    $('<td />', {
        'text': 'column1'
    }).appendTo(row);

    $('<td />', {
        'text': 'column2',
        'style': 'min-width:100px;'
    }).appendTo(row);
Pankaj Garg
  • 1,272
  • 15
  • 21
  • While this may be an answer, it is not very useful to a visitor later... Please add some explanation around your answer. – Jayan Dec 06 '15 at 05:23
12

You can use this great jQuery add table row function. It works great with tables that have <tbody> and that don't. Also it takes into the consideration the colspan of your last table row.

Here is an example usage:

// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
  • I can't see that being terribly useful. All it does is add an empty table row to a table. Typically, if not always, you want to add a new table row with some data in it. – Darryl Hein Mar 02 '09 at 17:48
  • 1
    But that is usually what you want. This function lets you add en empty row to any of your tables, no matter how many columns and row spans you have, thus making it UNIVERSAL function. You can carry on from there for example with $('.tbl tr:last td'). The whole point is to have universal function!!! – Uzbekjon Mar 04 '09 at 04:15
  • If your function also adds data into your new rows, you will not be able to use it the next time on your next project. What is the point?! It is in my opinion though, you don't need to share it... – Uzbekjon Mar 04 '09 at 04:19
  • If you propose the function that is not a part of a common package, please put the full function code here. Thank you. – Yevgeniy Afanasyev Sep 16 '15 at 05:38
11

My solution:

//Adds a new table row
$.fn.addNewRow = function (rowId) {
    $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>');
};

usage:

$('#Table').addNewRow(id1);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ricky Gummadi
  • 4,559
  • 2
  • 41
  • 67
  • so what if there is no `tbody` in table..?? means there can be row directly inside `` element, even if without any header.
    – shashwat May 18 '12 at 11:37
  • I would highly recommend you have your markup with so its up to the HTML 5 standards, if not then you can always do $(this).append(' '); that just appends a row in the table. – Ricky Gummadi May 22 '12 at 22:07
  • I think if you're going to make this a function you could perhaps return a jQuery object for the new row so it's chainable. – Kias Dec 22 '13 at 19:53
10

Neil's answer is by far the best one. However things get messy really fast. My suggestion would be to use variables to store elements and append them to the DOM hierarchy.

HTML

<table id="tableID">
    <tbody>
    </tbody>
</table>

JAVASCRIPT

// Reference to the table body
var body = $("#tableID").find('tbody');

// Create a new row element
var row = $('<tr>');

// Create a new column element
var column = $('<td>');

// Create a new image element
var image = $('<img>');
image.attr('src', 'img.png');
image.text('Image cell');

// Append the image to the column element
column.append(image);
// Append the column to the row element
row.append(column);
// Append the row to the table body
body.append(row);
Community
  • 1
  • 1
GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
9
<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

Write with a javascript function

document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';
Jakir Hossain
  • 2,457
  • 18
  • 23
9

I found this AddRow plugin quite useful for managing table rows. Though, Luke's solution would be the best fit if you just need to add a new row.

Community
  • 1
  • 1
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
8

This is my solution

$('#myTable').append('<tr><td>'+data+'</td><td>'+other data+'</td>...</tr>');
Daniel Ortegón
  • 315
  • 2
  • 8
7

Here is some hacketi hack code. I wanted to maintain a row template in an HTML page. Table rows 0...n are rendered at request time, and this example has one hardcoded row and a simplified template row. The template table is hidden, and the row tag must be within a valid table or browsers may drop it from the DOM tree. Adding a row uses counter+1 identifier, and the current value is maintained in the data attribute. It guarantees each row gets unique URL parameters.

I have run tests on Internet Explorer 8, Internet Explorer 9, Firefox, Chrome, Opera, Nokia Lumia 800, Nokia C7 (with Symbian 3), Android stock and Firefox beta browsers.

<table id="properties">
<tbody>
  <tr>
    <th>Name</th>
    <th>Value</th>
    <th>&nbsp;</th>
  </tr>
  <tr>
    <td nowrap>key1</td>
    <td><input type="text" name="property_key1" value="value1" size="70"/></td>
    <td class="data_item_options">
       <a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a>
    </td>
  </tr>
</tbody>
</table>

<table id="properties_rowtemplate" style="display:none" data-counter="0">
<tr>
 <td><input type="text" name="newproperty_name_\${counter}" value="" size="35"/></td>
 <td><input type="text" name="newproperty_value_\${counter}" value="" size="70"/></td>
 <td><a class="buttonicon" href="javascript:deleteRow()" title="Delete row" onClick="deleteRow(this); return false;"></a></td>
</tr>
</table>
<a class="action" href="javascript:addRow()" onclick="addRow('properties'); return false" title="Add new row">Add row</a><br/>
<br/>

- - - - 
// add row to html table, read html from row template
function addRow(sTableId) {
    // find destination and template tables, find first <tr>
    // in template. Wrap inner html around <tr> tags.
    // Keep track of counter to give unique field names.
    var table  = $("#"+sTableId);
    var template = $("#"+sTableId+"_rowtemplate");
    var htmlCode = "<tr>"+template.find("tr:first").html()+"</tr>";
    var id = parseInt(template.data("counter"),10)+1;
    template.data("counter", id);
    htmlCode = htmlCode.replace(/\${counter}/g, id);
    table.find("tbody:last").append(htmlCode);
}

// delete <TR> row, childElem is any element inside row
function deleteRow(childElem) {
    var row = $(childElem).closest("tr"); // find <tr> parent
    row.remove();
}

PS: I give all credits to the jQuery team; they deserve everything. JavaScript programming without jQuery - I don't even want think about that nightmare.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Whome
  • 10,181
  • 6
  • 53
  • 65
7
<tr id="tablerow"></tr>

$('#tablerow').append('<tr>...</tr><tr>...</tr>');
Vivek S
  • 2,010
  • 1
  • 13
  • 15
7

I Guess i have done in my project , here it is:

html

<div class="container">
    <div class = "row">
    <div class = "span9">
        <div class = "well">
          <%= form_for (@replication) do |f| %>
    <table>
    <tr>
      <td>
          <%= f.label :SR_NO %>
      </td>
      <td>
          <%= f.text_field :sr_no , :id => "txt_RegionName" %>
      </td>
    </tr>
    <tr>
      <td>
        <%= f.label :Particular %>
      </td>
      <td>
        <%= f.text_area :particular , :id => "txt_Region" %>
      </td>
    </tr>
    <tr>
      <td>
        <%= f.label :Unit %>
      </td>
      <td>
        <%= f.text_field :unit ,:id => "txt_Regio" %>
      </td>
      </tr>
      <tr>

      <td> 
        <%= f.label :Required_Quantity %>
      </td>
      <td>
        <%= f.text_field :quantity ,:id => "txt_Regi" %>
      </td>
    </tr>
    <tr>
    <td></td>
    <td>
    <table>
    <tr><td>
    <input type="button"  name="add" id="btn_AddToList" value="add" class="btn btn-primary" />
    </td><td><input type="button"  name="Done" id="btn_AddToList1" value="Done" class="btn btn-success" />
    </td></tr>
    </table>
    </td>
    </tr>
    </table>
    <% end %>
    <table id="lst_Regions" style="width: 500px;" border= "2" class="table table-striped table-bordered table-condensed">
    <tr>
    <td>SR_NO</td>
    <td>Item Name</td>
    <td>Particular</td>
    <td>Cost</td>
    </tr>
    </table>
    <input type="button" id= "submit" value="Submit Repication"  class="btn btn-success" />
    </div>
    </div>
    </div>
</div>

js

$(document).ready(function() {     
    $('#submit').prop('disabled', true);
    $('#btn_AddToList').click(function () {
     $('#submit').prop('disabled', true);
    var val = $('#txt_RegionName').val();
    var val2 = $('#txt_Region').val();
    var val3 = $('#txt_Regio').val();
    var val4 = $('#txt_Regi').val();
    $('#lst_Regions').append('<tr><td>' + val + '</td>' + '<td>' + val2 + '</td>' + '<td>' + val3 + '</td>' + '<td>' + val4 + '</td></tr>');
    $('#txt_RegionName').val('').focus();
    $('#txt_Region').val('');
        $('#txt_Regio').val('');
        $('#txt_Regi').val('');
    $('#btn_AddToList1').click(function () {
         $('#submit').prop('disabled', false).addclass('btn btn-warning');
    });
      });
});
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
SNEH PANDYA
  • 797
  • 7
  • 22
7

if you have another variable you can access in <td> tag like that try.

This way I hope it would be helpful

var table = $('#yourTableId');
var text  = 'My Data in td';
var image = 'your/image.jpg'; 
var tr = (
  '<tr>' +
    '<td>'+ text +'</td>'+
    '<td>'+ text +'</td>'+
    '<td>'+
      '<img src="' + image + '" alt="yourImage">'+
    '</td>'+
  '</tr>'
);

$('#yourTableId').append(tr);
RKRK
  • 1,284
  • 5
  • 14
  • 18
MEAbid
  • 560
  • 7
  • 11
6
<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
Pavel Shkleinik
  • 6,298
  • 2
  • 24
  • 36
6

As i have also got a way too add row at last or any specific place so i think i should also share this:

First find out the length or rows:

var r=$("#content_table").length;

and then use below code to add your row:

$("#table_id").eq(r-1).after(row_html);
Jaid07
  • 153
  • 1
  • 4
6

To add a good example on the topic, here is working solution if you need to add a row at specific position.

The extra row is added after the 5th row, or at the end of the table if there are less then 5 rows.

var ninja_row = $('#banner_holder').find('tr');

if( $('#my_table tbody tr').length > 5){
    $('#my_table tbody tr').filter(':nth-child(5)').after(ninja_row);
}else{
    $('#my_table tr:last').after(ninja_row);
}

I put the content on a ready (hidden) container below the table ..so if you(or the designer) have to change it is not required to edit the JS.

<table id="banner_holder" style="display:none;"> 
    <tr>
        <td colspan="3">
            <div class="wide-banner"></div>
        </td>   
    </tr> 
</table>
d.raev
  • 9,216
  • 8
  • 58
  • 79
5
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

will add a new row to the first TBODY of the table, without depending of any THEAD or TFOOT present. (I didn't find information from which version of jQuery .append() this behavior is present.)

You may try it in these examples:

<table class="t"> <!-- table with THEAD, TBODY and TFOOT -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t"> <!-- table with two TBODYs -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
  <tr><td>1</td><td>2</td></tr>
</tbody>
<tbody>
  <tr><td>3</td><td>4</td></tr>
</tbody>
<tfoot>
  <tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>

<table class="t">  <!-- table without TBODY -->
<thead>
  <tr><th>h1</th><th>h2</th></tr>
</thead>
</table><br>

<table class="t">  <!-- table with TR not in TBODY  -->
  <tr><td>1</td><td>2</td></tr>
</table>
<br>
<table class="t">
</table>

<script>
$('.t').append('<tr><td>a</td><td>a</td></tr>');
</script>

In which example a b row is inserted after 1 2, not after 3 4 in second example. If the table were empty, jQuery creates TBODY for a new row.

Alexey Pavlov
  • 185
  • 1
  • 2
  • 12
5

If you are using Datatable JQuery plugin you can try.

oTable = $('#tblStateFeesSetup').dataTable({
            "bScrollCollapse": true,
            "bJQueryUI": true,
            ...
            ...
            //Custom Initializations.
            });

//Data Row Template of the table.
var dataRowTemplate = {};
dataRowTemplate.InvoiceID = '';
dataRowTemplate.InvoiceDate = '';
dataRowTemplate.IsOverRide = false;
dataRowTemplate.AmountOfInvoice = '';
dataRowTemplate.DateReceived = '';
dataRowTemplate.AmountReceived = '';
dataRowTemplate.CheckNumber = '';

//Add dataRow to the table.
oTable.fnAddData(dataRowTemplate);

Refer Datatables fnAddData Datatables API

Praveena M
  • 522
  • 4
  • 10
5

In a simple way:

$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');
vipul sorathiya
  • 1,318
  • 12
  • 23
  • Could you please elaborate more your answer adding a little more description about the solution you provide? – abarisone Jun 16 '15 at 13:09
5

Try this : very simple way

$('<tr><td>3</td></tr><tr><td>4</td></tr>').appendTo("#myTable tbody");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="myTable">
  <tbody>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
  </tbody>
</table>
Rajkumar
  • 1,017
  • 9
  • 12
5

The answers above are very helpful, but when student refer this link to add data from form they often require a sample.

I want to contribute an sample get input from from and use .after() to insert tr to table using string interpolation.

function add(){
  let studentname = $("input[name='studentname']").val();
  let studentmark = $("input[name='studentmark']").val();

  $('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}

function add(){
let studentname = $("input[name='studentname']").val();
let studentmark = $("input[name='studentmark']").val();

$('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>
<form>
<input type='text' name='studentname' />
<input type='text' name='studentmark' />
<input type='button' onclick="add()" value="Add new" />
</form>
<table id='student'>
  <thead>
    <th>Name</th>
    <th>Mark</th>
  </thead>
</table>
</body>
</html>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
4

If you want to add row before the <tr> first child.

$("#myTable > tbody").prepend("<tr><td>my data</td><td>more data</td></tr>");

If you want to add row after the <tr> last child.

$("#myTable > tbody").append("<tr><td>my data</td><td>more data</td></tr>");
Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36
4

I have tried the most upvoted one, but it did not work for me, but below works well.

$('#mytable tr').last().after('<tr><td></td></tr>');

Which will work even there is a tobdy there.

Duke
  • 35,420
  • 13
  • 53
  • 70
4

)Daryl:

You can append it to the tbody using the appendTo method like this:

$(() => {
   $("<tr><td>my data</td><td>more data</td></tr>").appendTo("tbody");
});

You'll probably want to use the latest JQuery and ECMAScript. Then you can use a back-end language to add your data to the table. You can also wrap it in a variable like so:

$(() => {
  var t_data = $('<tr><td>my data</td><td>more data</td></tr>');
  t_data.appendTo('tbody');
});
Mark
  • 167
  • 1
  • 3
  • 13
2

Add tabe row using JQuery:

if you want to add row after last of table's row child, you can try this

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

if you want to add row 1st of table's row child, you can try this

$('#myTable tr').after('<tr>...</tr><tr>...</tr>');
Rizwan
  • 3,741
  • 2
  • 25
  • 22
2

Pure JS is quite short in your case

myTable.firstChild.innerHTML += '<tr><td>my data</td><td>more data</td></tr>'

function add() {
  myTable.firstChild.innerHTML+=`<tr><td>date</td><td>${+new Date}</td></tr>`
}
td {border: 1px solid black;}
<button onclick="add()">Add</button><br>
<table id="myTable"><tbody></tbody> </table>

(if we remove <tbody> and firstChild it will also works but wrap every row with <tbody>)

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2
  1. Using jQuery .append()
  2. Using jQuery .appendTo()
  3. Using jQuery .after()
  4. Using Javascript .insertRow()
  5. Using jQuery - add html row

Try This:

// Using jQuery - append
$('#myTable > tbody').append('<tr><td>3</td><td>Smith Patel</td></tr>');

// Using jQuery - appendTo
$('<tr><td>4</td><td>J. Thomson</td></tr>').appendTo("#myTable > tbody");

// Using jQuery - add html row
let tBodyHtml = $('#myTable > tbody').html();
tBodyHtml += '<tr><td>5</td><td>Patel S.</td></tr>';
$('#myTable > tbody').html(tBodyHtml);

// Using jQuery - after
$('#myTable > tbody tr:last').after('<tr><td>6</td><td>Angel Bruice</td></tr>');

// Using JavaScript - insertRow
const tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const newRow = tableBody.insertRow(tableBody.rows.length);
newRow.innerHTML = '<tr><td>7</td><td>K. Ashwin</td></tr>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>John Smith</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Tom Adam</td>
        </tr>
    </tbody>
</table>
Sahil Thummar
  • 1,926
  • 16
  • 16
0

This could also be done :

$("#myTable > tbody").html($("#myTable > tbody").html()+"<tr><td>my data</td><td>more data</td></tr>")
Prashant
  • 375
  • 2
  • 8
  • That seems quite complicated and maybe even slower for the browser/JS to deal with as it needs to parse a lot more HTML. – Darryl Hein Mar 30 '17 at 15:07
0

To add a new row at the last of current row, you can use like this

$('#yourtableid tr:last').after('<tr>...</tr><tr>...</tr>');

You can append multiple row as above. Also you can add inner data as like

$('#yourtableid tr:last').after('<tr><td>your data</td></tr>');

in another way you can do like this

let table = document.getElementById("tableId");

let row = table.insertRow(1); // pass position where you want to add a new row


//then add cells as you want with index
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
let cell3 = row.insertCell(3);


//add value to added td cell
 cell0.innerHTML = "your td content here";
 cell1.innerHTML = "your td content here";
 cell2.innerHTML = "your td content here";
 cell3.innerHTML = "your td content here";
Hemant N. Karmur
  • 840
  • 1
  • 7
  • 21
0

Here, You can Just Click on button then you will get Output. When You Click on Add row button then one more row Added.

I hope It is very helpful.

<html> 

<head> 
    <script src= 
            "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 

    <style> 
        table { 
            margin: 25px 0; 
            width: 200px; 
        } 

        table th, table td { 
            padding: 10px; 
            text-align: center; 
        } 

        table, th, td { 
            border: 1px solid; 
        } 
    </style> 
</head> 

<body> 

    <b>Add table row in jQuery</b> 

    <p> 
        Click on the button below to 
        add a row to the table 
    </p> 

    <button class="add-row"> 
        Add row 
    </button> 

    <table> 
        <thead> 
            <tr> 
                <th>Rows</th> 
            </tr> 
        </thead> 
        <tbody> 
            <tr> 
                <td>This is row 0</td> 
            </tr> 
        </tbody> 
    </table> 

    <!-- Script to add table row -->
    <script> 
        let rowno = 1; 
        $(document).ready(function () { 
            $(".add-row").click(function () { 
                rows = "<tr><td>This is row " 
                    + rowno + "</td></tr>"; 
                tableBody = $("table tbody"); 
                tableBody.append(rows); 
                rowno++; 
            }); 
        }); 
    </script> 
</body> 
</html>                  
Nikhil B
  • 93
  • 6
0
var html = $('#myTableBody').html();
html += '<tr><td>my data</td><td>more data</td></tr>';
$('#myTableBody').html(html);

or

$('#myTableBody').html($('#myTableBody').html() + '<tr><td>my data</td><td>more data</td></tr>');
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-1

TIP: Inserting rows in html table via innerHTML or .html() is not valid in some browsers (similar IE9), and using .append("<tr></tr>") is not good suggestion in any browser. best and fastest way is using the pure javascript codes.

for combine this way with jQuery, only add new plugin similar this to jQuery:

$.fn.addRow=function(index/*-1: add to end  or  any desired index*/, cellsCount/*optional*/){
    if(this[0].tagName.toLowerCase()!="table") return null;
    var i=0, c, r = this[0].insertRow((index<0||index>this[0].rows.length)?this[0].rows.length:index);
    for(;i<cellsCount||0;i++) c = r.insertCell(); //you can use c for set its content or etc
    return $(r);
};

And now use it in whole the project similar this:

var addedRow = $("#myTable").addRow(-1/*add to end*/, 2);
Hassan Sadeghi
  • 1,316
  • 2
  • 8
  • 14