ChatGPT解决这个技术问题 Extra ChatGPT

Add table row in jQuery

What is the best method in jQuery to add an additional row to a table as the last row?

Is this acceptable?

$('#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)?

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.
FYI - Avoid using multiple appends (slows down performance tremendously), rather build up your string or use JavaScript join which is much faster.
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 :)

C
Community

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>');

N
Nick Veys

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.


C
Community

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>');

nice, +1, me too
S
Sohel Ahmed Mesaniya

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>");

A
AminM

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.


p
pimvdb

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>

C
Community

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


If you have multiple tbody you can get multiple inserts
Yes you can :) You can try $("SELECTOR").last() to limit your tag collection
D
Darryl Hein

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

$("#tableId").last().append("<tr><td>New row</td></tr>");

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.
A
Anton vBR

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($('') .append($('').append("text1")) .append($('').append("text2")) .append($('').append("text3")) .append($('').append("text4")) )

Firstname Lastname Age City
Jill Smith 50 New York


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
I think you need to call an update function of some sort. Hade to tell without an example.
D
Dominic

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() );

...

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.
A
Anik Islam Abhi

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>');

E
Erick Robertson

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);

I think this should be a new question, instead of an answer to an existing one...
U
Uzbekjon

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'));

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.
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!!!
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...
If you propose the function that is not a part of a common package, please put the full function code here. Thank you.
P
Pankaj Garg
    // 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);

While this may be an answer, it is not very useful to a visitor later... Please add some explanation around your answer.
P
Peter Mortensen

My solution:

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

usage:

$('#Table').addNewRow(id1);

so what if there is no tbody in table..?? means there can be row directly inside <table> element, even if without any header.
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.
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.
C
Community

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);

J
Jakir Hossain
<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>';

C
Community

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.


D
Daniel Ortegón

This is my solution

$('#myTable').append('<tr><td>'+data+'</td><td>'+other data+'</td>...</tr>');

P
Peter Mortensen

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.


V
Vivek S
<tr id="tablerow"></tr>

$('#tablerow').append('<tr>...</tr><tr>...</tr>');

S
Shaunak D

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');
    });
      });
});

R
RKRK

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);

J
Jaid07

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);

d
d.raev

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>

S
Shaunak D
<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>")

A
Alexey Pavlov
$('#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.


P
Praveena M

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


v
vipul sorathiya

In a simple way:

$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');

Could you please elaborate more your answer adding a little more description about the solution you provide?
r
rajmobiapp

Try this : very simple way

$('34').appendTo("#myTable tbody");

1
2