增加表行脚本

时间:2016-02-02 10:14:34

标签: javascript

我有这个增量行脚本,允许用户使用'添加行'添加行。按钮。该按钮添加了行,但从我看到它并没有为新字段分配新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>
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您没有在代码中的任何位置使用计数器变量。只需更新以下行即可开始工作。

newFields.id = 'FieldName_0' + counter;