递增表行脚本

Increment Table Row Script

本文关键字:脚本      更新时间:2023-09-26

>我有这个增量行脚本,允许用户使用"添加行"按钮向表中添加行。该按钮添加了该行,但据我所知,它不会为新字段分配新 ID,即第一行是FieldName_0,下一行应该是FieldName_1等。

然后我有代码,提交时会遍历每个字段并插入到表中。

不确定为什么没有为字段分配新 ID。任何帮助表示赞赏。

请注意,该按钮在我的程序中有效,但在下面的代码段中它不起作用,希望仅编写的代码就足够了。

< script language = "javascript" >
  var counter = 0;
// Start a counter. Yes, at 0
function add_row_desc() {
  counter++;
  // I find it easier to start the incrementing of the counter here.
  var newFields = document.getElementById('newrowdesc').cloneNode(true);
  newFields.id = '';
  newFields.style.display = '';
  var newField = newFields.childNodes;
  for (var i = 0; i < newField.length; i++) {
    var theName = newField[i].name
    if (theName)
      newField[i].name = theName + counter;
    // This will change the 'name' field by adding an auto incrementing number at the end. This is important.
  }
  var insertHere = document.getElementById('newrowdesc');
  // Inside the getElementById brackets is the name of the div class you will use.
  insertHere.parentNode.insertBefore(newFields, insertHere);
}
< /script>
<table class="table table-striped table-condensed">
  <thead>
    <tr>
      <th class="col-sm-2">Quantity</th>
      <th class="col-sm-5">Job Description</th>
      <th class="col-sm-2">Total PP</th>
      <th class="col-sm-2">Finished Size</th>
      <th class="col-sm-1"></th>
    </tr>
  </thead>
  <tbody>
    <tr id="rowdesc">
      <td>
        <input name="JobQuantity_0" type="text" class="form-control" />
      </td>
      <td>
        <input name="JobDescription_0" type="text" class="form-control" />
      </td>
      <td>
        <input name="JobTotalPP_0" type="text" class="form-control" />
      </td>
      <td>
        <input name="JobFinSize_0" type="text" class="form-control" />
      </td>
      <td>
        <input type="button" class="form-control" id="add_row_desc()" onclick="add_row_desc()" value="Add Row" />
      </td>
    </tr>
    <tr id="newrowdesc" style="display: none;">
      <td>
        <input type="text" class="form-control" />
      </td>
      <td>
        <input type="text" class="form-control" />
      </td>
      <td>
        <input type="text" class="form-control" />
      </td>
      <td>
        <input type="text" class="form-control" />
      </td>
      <td></td>
    </tr>

您没有在代码中的任何位置使用计数器变量。 只需更新以下行,它应该可以正常工作。

newFields.id = 'FieldName_0' + counter;