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)?
will add a new row to the first
TBODY
of the table, without depending of anyTHEAD
orTFOOT
present. (I didn't find information from which version of jQuery.append()
this behavior is present.)You may try it in these examples:
In which example
a b
row is inserted after1 2
, not after3 4
in second example. If the table were empty, jQuery createsTBODY
for a new row.jQuery has a built-in facility to manipulate DOM elements on the fly.
You can add anything to your table like this:
The
$('<some-tag>')
thing in jQuery is a tag object that can have severalattr
attributes that can be set and get, as well astext
, 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.
What if you had a
<tbody>
and a<tfoot>
?Such as:
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
.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.
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):
I hope it helps.
if you have another variable you can access in
<td>
tag like that try.This way I hope it would be helpful