Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert new rows in some position in table

I have page with table. In tbody I show data via angularjs. In thead I have same row as in tbody, but its empty, and when I filled input field and click somewhere (focus lost), one row adds to my table (thead). And I need to make some flag on filled row, as like - rowAdded = true, because without that I clicking on input of one row and rows adds. And one more problem is that rows adds to the end of table. it's 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);
}

There is my example in plunker: http://plnkr.co/edit/rcnwv0Ru8Hmy7Jrf9b1C?p=preview

like image 911
HUSTLIN Avatar asked Nov 10 '22 07:11

HUSTLIN


1 Answers

Is this 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>
like image 74
joyBlanks Avatar answered Nov 14 '22 21:11

joyBlanks