I'd do it like this:
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of rows to insert');
} else {
$tbody = $('table tbody');
$row = $tbody.find('tr:last');
additionalRows = new Array(numNewRows + 1).join($row[0].outerHTML);
$tbody.append(additionalRows);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>Col1</th>
<th>Col2</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<input type="number" id="insert-rows-amnt" />
<button id="add-row" type="button">Add Rows</button>
Firstly, don't trust user input, verify you actually have a number, try to parse it and be explicit. Always use the radix, parseInt()
can try to be too clever for its own good. The result could be NaN or a number, so check for these:
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
If you're using JQuery
, cache found objects, finding them isn't free, a search is done every time you pass a string selector, so if you've already found it, use it. This ins't going to set the world on fire, but it's a good habit to get into.
Onto the meat of the method, there are two methods for inserting HTML quickly. HTML updates are like Excel Worksheet updates, no small amount of processing goes on when you change the dom. Most of the time this is negligible, but if you're inserting a huge amount of html it's something to be aware of.
You could create a document fragment and append nodes to it. This gives the benefit of working with objects rather than strings so is less error prone. The essence of it is you create the fragment in memory and insert it once.
You can create the html as a string and insert it, it's a single dom update, but more error prone as you're string building. This case is simple enough for it to be a good option though.
new Array(numNewRows + 1).join($row[0].outerHTML);
This replicates a string x number of times. It works by initialising an array of x dimensions and then joining it using a given string as the text between the elements.