Andrus Andrus - 1 month ago 8
ASP.NET (C#) Question

How to add row after last row in table

Table contains hidden template row and zero or more visible data rows.
In end of table there is add button which shoud add new empty row to end of table.

I tried

function addVariablesRow() {
var t = document.getElementById("reportVariablesTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}


but it adds row before last row to table. How to add row after last row to table ?

ASP.NET MVC4 application, bootstrap 3 modal, jquery, jquery-ui are used.

html:

<div class="modal" id="reportVariables" tabindex="-1" role="dialog" aria-labelledby="reportVariablesLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-condensed table-striped" id="reportVariablesTable">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Calculate</th>
</tr>
</thead>
<tbody>
<!-- first row is hidden add template row -->
<tr style='display:none'>
<td>
<input type="text" name="name">
</td>

<td>
<textarea name="valuetostore"></textarea>
</td>

<td>
<select class="totaltype-select" id="totaltype" name="totaltype">
<option value=""></option>
<option value="Sum">Summary</option>
<option value="Lowest">Smallest</option>
<option value="Highest">Biggers</option>
</select>
</td>
</tr>

<!-- other are visible data rows -->
<tr>
<td>
<input type="text" name="name" value="variable1">
</td>

<td>
<textarea name="valuetostore">a-b</textarea>
</td>

<td>
<select class="totaltype-select" id="totaltype" name="totaltype">
<option value=""></option>
<option value="Sum">Summary</option>
<option value="Lowest" selected>Smallest</option>
<option value="Highest">Biggers</option>
</select>
</td>
</tr>
... remaining rows
</tbody>
</table>
<button onclick="addVariablesRow();">+</button>

</div>
</div>
</div>
</div>


Update

I ned to clone template row which is first in body and make new row visible.
I tried:

function addVariablesRow() {
var $t = $("#reportVariablesTable");
var $row = $($t.find("tr")[1]);
var r = $row.clone();
r[0].style.display = "";
r.appendTo($t);
}


Is this best code ? Maybe it is bettet to find template row as first in body?

Answer

As you mentioned JQuery is an option, you could use something like this:

function addVariablesRow() {
    var $t = $("#reportVariablesTable");
    var $row = $t.find("tbody tr").first();
    var $newRow = $row.clone();
    $newRow.appendTo($t).show();
}