在html表中动态添加新行

时间:2019-03-14 22:11:46

标签: jquery

当用户在任意行的最后enter中按下cell键时,我可以将新行动态添加到html表中。

JSFiddle DEMO

但是,当前,无论当前行的位置如何,它都会添加新行。我只想在用户在最后一个enter的最后一个td中按下tr键时添加新行

3 个答案:

答案 0 :(得分:2)

每次添加新行时,您都将keyup()处理函数连接到该行的最后一个单元格。而是给最后一个单元格一个类,并将addnewrow绑定到该类。然后在添加行之前,首先从所有现有单元格中删除类,然后添加行。这样,只有最后一行的最后一个单元格才具有触发添加新行的类。

$(function() {
  // Change the selector if needed
  var $table = $('.mt-table-edit');

  addNewRow();


  function addNewRow() {
    //get row template. We must use html() for new instance other event handler will get attached to last row
    var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input class='addNew' /></td></tr>");


    // add template after the last row
    $table.find("tbody:last-child").append($tr);

    // focus on firt input of newly added row
    $tr.find("td:first input").focus();
  }

  $table.on('keyup', '.addNew', function(e){    
    if (event.keyCode === 13) {
        $(this).removeClass('addNew');
        addNewRow();
      }
  });
});

Here is the updated/working fiddle

答案 1 :(得分:2)

如果您不想注册键盘侦听器,则需要将其与td解除绑定。该代码段将使用您的addNewRow()并设置一个previousLastTable并将与previousLastTable.off("keyup");解除绑定,从而删除监听器。唯一活动的侦听器将是最后一个td的最后一个tr

$(function() {
  // Change the selector if needed
  var $table = $('.mt-table-edit');

  addNewRow();

  var previousLastTable;


  function addNewRow() {
    //get row template. We must use html() for new instance other event handler will get attached to last row
    var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");

    if (previousLastTable) {
      previousLastTable.off("keyup");
    }


    $tr.find("td").eq($tr.find("td").length - 1).keyup(function(e) {
      if (event.keyCode === 13) {
        addNewRow();
      }
    });

    // add template after the last row
    $table.find("tbody:last-child").append($tr);

    // focus on firt input of newly added row
    $tr.find("td:first input").focus();

    previousLastTable = $tr.find("td").eq($tr.find("td").length - 1);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  To add new row press enter key in the last cell of the row
</p>
<table class="mt-table-edit">
  <thead>
    <tr>
      <th>Street</th>
      <th>State</th>
      <th>City</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

答案 2 :(得分:0)

@NilsKähler和@Nawed Khan的两个答案都可能基于我的最初帖子。但是,每行还具有删除选项。用户可以删除任何行。我的JavaScript确实会删除单个行。 (对不起,为了简洁起见,我省略了该部分。我的错)。 对我来说,这意味着解决方案无法按原样工作。(但是我投票给您,因为这是初始帖子的正确答案)

我只需要最简单的方法来查找当前行是否是表的最后一行。这是我的工作演示。

where 1 not in (null)

DEMO