How to insert new rows at a specific position in a table

I have a page with a table. In tbody I show data through angularjs . In thead , I have the same row as in tbody , but it is empty, and when I filled in the input field and click somewhere (loss of focus), one row adds my table ( thead ). And I need to make some flag on the filled line, as if - rowAdded = true , because without it I click on the input of one line and adds the lines. And another problem is that the rows are added to the end of the table . it all works on this script:

 var tbody = $('.table-timesheet thead'); tbody.on('blur', ':text', function () { var tr = $(this).closest('tr'), notEmpty = $(':text', tr).filter(function () { return $.trim($(this).val()) != ''; }).length; if (notEmpty) { $('.note-input').css('width', '88%').css('float', 'left'); $('.timesheet-delete-button').css('display', 'block'); //tr.clone(true).appendTo(tbody).find(':text').val(''); insRow(); } }); function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('table-body').deleteRow(i); } function insRow() { var table = document.getElementById('table-body'); var newRow = table.rows[1].cloneNode(true); var len = table.rows.length; newRow.cells[0].innerHTML = len; var inp1 = newRow.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; var inp2 = newRow.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; table.appendChild(newRow); } 

My plunker has my example: http://plnkr.co/edit/rcnwv0Ru8Hmy7Jrf9b1C?p=preview

+5
source share
1 answer

This is what you are looking for

 function insRow(ind){ var table = document.getElementById('table-body'); var newRow = table.rows[1].cloneNode(true); var len = table.rows.length; newRow.cells[0].innerHTML = ind!==undefined ? ind : len; if(ind!==undefined) $(table).find('tr:eq('+ind+')').before(newRow); else table.appendChild(newRow); } insRow(2); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table-body"> <tbody> <tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td>3</td></tr> </tbody> </table> 
+1
source

All Articles